package com.malbbmsomanager;

/************PDADBWebServiceBBM - Live Server*****************/
/************PDADBWebServiceBestBuy - Web Server**********************/
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONStringer;
import com.malbbmsomanager.adapter.DM_BBM_Connection_Detector;
import com.malbbmsomanager.management.DM_BBM_Item_Master;
import com.malbbmsomanager.receipt.DM_BBM_InvoiceSalesReceipt;
import com.malbbmsomanager.reports.DM_BBM_Reports_Generator;
import com.malbbmsomanager.retailmanagement.DM_BBM_Retailer_Master;
import com.malbbmsomanager.transactions.DM_BBM_InvoiceSalesEditOrderDetails;
import com.malbbmsomanager.transactions.DM_BBM_InvoiceSalesOrder;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class DM_BBM_InvoiceMenu extends Activity implements
		ActionBar.OnNavigationListener {

	// action bar
	private ActionBar actionBar;

	// Database Name
	private static final String DBNAME = "dminvoicemanagerbbm.db";
	private static final String TAG = null;
	// Master Tables BBM
	private String FDEBTOR_TABLE = "fDebtor";
	private String FTAXDET_TABLE = "FtaxDet";
	private String FBRAND_TABLE = "FBrand";
	private String FITEMS_TABLE = "FItems";
	private String FCURRENCY_TABLE = "fCurrency";
	private String FSALREP_TABLE = "fSalRep";
	private String FCOMPANYSETTINGS_TABLE = "fCompanySetting";
	private String FLOCATION_TABLE = "fLocation";
	private String FITEMFREQTY_TABLE = "fItemFreeQty";
	private String FCOMPANYBRANCH_TABLE = "FCompanyBranch";
	private String FCOMPANYDM_TABLE = "fCompanyDM";
	// ****
	private String SERVER_DB_LIST = "serverdb";
	private String USER_SETTINGS = "usersettings";
	private String YEARS_LIST = "FYearsList";
	private String MONTH_LIST = "FMonthList";
	private String SERVER_DETAILS = "serverinfo";
	// ****Main Transaction Table****
	private String FORDHED_TABLE = "FOrdHed";
	private String FORDDET_TABLE = "FOrdDet";
	private String FORDTAXDT_TABLE = "FOrdTaxDt";
	private String FORDTAXRG_TABLE = "FOrdTaxRg";
	// Master Tables BBM
	private String FDDBNOTE_TABLE = "fddbnote";
	private String FAREA_TABLE = "fArea";
	private String FITEMPRI_TABLE = "fItemPri";
	private String FTAXHED_TABLE = "fTaxHed";
	private String FTAX_TABLE = "fTax";
	private String FCONTROL_TABLE = "fControlResult";
	private String FDEBTAX_TABLE = "fDebTax";
	private String FGLFACC_TABLE = "fglfacc";
	private String FBANK_TABLE = "fbank";

	// Receipt Tranactiob
	private String FPRECHED_TABLE = "FPRecHed";
	private String FPRECDET_TABLE = "FPRecDet";

	// private PBDatabaseAdapter dbHelper;
	ProgressDialog mProgressDialog;
	private SQLiteDatabase mydb;
	String TagId;
	String connectionURL, username, lrepprefix, lreploccode, serverDbName,
			printerMac;
	String currentUserServerDB;
	int arrayLength = 0;
	int settingsActive;
	// flag for Internet connection status
	Boolean isInternetPresent = false;
	AlertDialog InvoiceHeaderAlert = null;
	// Connection detector class
	DM_BBM_Connection_Detector cd;// ConnectionDetector
	private CountDownTimer mCountDown;

	ArrayList<String> arFinvHed = new ArrayList<String>();
	ArrayList<String> arFinvDet = new ArrayList<String>();

	ArrayList<String> arFOrdTaxDt = new ArrayList<String>();
	ArrayList<String> arFOrdTaxRg = new ArrayList<String>();

	ArrayList<String> arFPRecHed = new ArrayList<String>();
	ArrayList<String> arFPRecDet = new ArrayList<String>();

	String SIupSummary;
	String result = null;
	String resultp = null;
	InputStream is = null;
	InputStream isp = null;
	StringBuilder sb = null;
	StringBuilder sbp = null;
	StringBuilder sbNew;
	String resultNew, FresultB;
	InputStream isNew;
	JSONArray jArray;
	int fInvHedCount = 0, fOrdHedCount = 0;
	int fInvHedCountFail = 0, fOrdHedCountFail = 0;
	String ReadRefErrorUpload;
	Cursor selectInvHeadDetailsReChk = null, selectInvDetailsDataReChk = null;
	Cursor selectInvHeadDetailsUpdate = null,
			selectInvDetailsDataUpdate = null;
	Cursor selectInvHeadDetailsChkFail = null,
			selectInvDetailsDataChkFail = null;
	Date date;
	int NetFail = 0;
	// Title navigation Spinner data
	/*
	 * private ArrayList<SpinnerNavItem> navSpinner;
	 * 
	 * // Navigation adapter private TitleNavigationAdapter adapter;
	 */
	// Refresh menu item
	private MenuItem refreshMenuItem;
	SimpleDateFormat originalFormat = new SimpleDateFormat(
			"dd MM yyyy hh:mm:ss aa");
	SimpleDateFormat targetFormat = new SimpleDateFormat(
			"yyyy-MM-dd hh:mm:ss aa");

	SimpleDateFormat originalFormatTxn = new SimpleDateFormat("dd MM yyyy");
	SimpleDateFormat targetFormatTxn = new SimpleDateFormat("yyyy-MM-dd");

	final private static int DIALOG_SYNC_SUCCESS = 1;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dm_bbm_invoice_menu);

		cd = new DM_BBM_Connection_Detector(getApplicationContext());
		Calendar c1 = Calendar.getInstance();
		c1.set(2013, 6, 12);
		Calendar c2 = Calendar.getInstance();
		c2.set(2014, 6, 12);

		Date d1 = c1.getTime();
		Date d2 = c2.getTime();

		long diff = d2.getTime() - d1.getTime();
		int noofdays = (int) (diff / (1000 * 24 * 60 * 60));
		System.out.println(noofdays);
		Log.v(TAG, "DAYS :" + noofdays);

		actionBar = getActionBar();
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(true);
		actionBar.setDisplayHomeAsUpEnabled(false);

		/*
		 * Bundle bundle = getIntent().getExtras(); TagId =
		 * bundle.getString("TAGID");
		 */
		// creating connection detector class instance
		getConnectionUrl();
		currentuserTemp();
		// agentPrefixSalesOrder();
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor chkinvoice = null;
		/*
		 * mydb.execSQL("DROP TABLE IF EXISTS FPRecHed");
		 * mydb.execSQL("DROP TABLE IF EXISTS FPRecDet");
		 * mydb.execSQL("create table if not exists " + FPRECHED_TABLE +
		 * "(fpreched_id integer primary key autoincrement,RefNo text not null,ManuRef text not null,SaleRefNo text not null,RepCode text not null,TxnType text not null,Chqno text not null,ChqDate text not null,TxnDate text not null,CurCode text not null,CurRate1 text not null,DebCode text not null,TotalAmt text not null,BTotalAmt text not null,BankCur text not null,BankRate text not null,BankAmt text not null,BankCharge text not null,BBankChg text not null,GnLsCal text not null,DbAcc text not null,PayType text not null,PrtCopy text not null,GlPost text not null,Remarks text not null,CardSlipNo text not null,ExpDate text not null,CrdTypCode text not null,CCBankAmt text not null,GlBatch text not null,AddUser text not null,AddMach text not null,AddDate text not null,CurRate text not null,customer_name text not null,payTypeDes text not null,CACHAcNo text not null,CACHAcBank text not null,CusBankCode text not null,CusBankName text not null,ActiveState text not null,SyncState text not null,AllocatedOriAmount text not null,AllocatedAmount text not null);"
		 * );
		 * 
		 * mydb.execSQL("create table if not exists " + FPRECDET_TABLE +
		 * "(fprecdet_id	integer primary key autoincrement,RefNo text not null,RefNo1 text not null,SaleRefNo text not null,ManuRef text not null,TxnType text not null,TxnDate text not null,DtxnDate text not null,DtxnType text not null,DCurCode text not null,DCurRate text not null,OCurRate text not null,RepCode text not null,Amt text not null,BAmt text not null,GainLosAmt text not null,BnkChgs text not null,BBnkChgs text not null,AloAmt text not null,OvPayAmt text not null,OvPayBal text not null,SyncState text not null);"
		 * );
		 */
		Button addNewSalesOrder = (Button) findViewById(R.id.dmnewsalesorder);
		addNewSalesOrder.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {

				Intent myIntent = new Intent(DM_BBM_InvoiceMenu.this,
						DM_BBM_InvoiceSalesOrder.class);

				/*
				 * Intent myIntent = new Intent(view.getContext(),
				 * DM_BBM_InvoiceSalesOrder.class);
				 */
				/*
				 * myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
				 * Intent.FLAG_ACTIVITY_NEW_TASK);
				 */
				myIntent.putExtra("TAGID", "3");
				startActivity(myIntent);
				// finish();

			}

		});

		Button synchstocks = (Button) findViewById(R.id.synchstocks);
		synchstocks.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				isInternetPresent = cd.isConnectingToInternet();
				if (isInternetPresent) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							DM_BBM_InvoiceMenu.this);
					// Setting Dialog Title
					alertDialogBuilder.setTitle("DOWNLOAD STOCKS");
					// Setting Dialog Message
					alertDialogBuilder.setMessage("Sync Current Stocks");
					// set positive button: Yes message
					alertDialogBuilder.setPositiveButton("DOWNLOAD",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
									mydb = openOrCreateDatabase(DBNAME,
											Context.MODE_PRIVATE, null);
									new DownloadStocks().execute();
								}
							});
					// set negative button: No message
					alertDialogBuilder.setNegativeButton("CANCEL",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									// cancel the alert box and put a Toast to the
									// user
									dialog.cancel();
								}
							});

					AlertDialog alertDialog = alertDialogBuilder.create();
					// show alert
					alertDialog.show();
				} 

				else {
				// Internet connection is not present
				// Ask user to connect to Internet
				showAlertDialog(DM_BBM_InvoiceMenu.this,"No Internet Connection","You don't have internet connection...", false);
				}
			}

		});

		Button synchdata = (Button) findViewById(R.id.synchdata);
		synchdata.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				isInternetPresent = cd.isConnectingToInternet();
				if (isInternetPresent) {
					AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
							DM_BBM_InvoiceMenu.this);
					// Setting Dialog Title
					alertDialogBuilder.setTitle("SYNC DETAILS");
					// Setting Dialog Message
					alertDialogBuilder.setMessage("Sync Master Data");
					// set positive button: Yes message
					alertDialogBuilder.setPositiveButton("SYNC",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.cancel();
									mydb = openOrCreateDatabase(DBNAME,
											Context.MODE_PRIVATE, null);
									new SyncMasterDetails().execute();
								}
							});
					// set negative button: No message
					alertDialogBuilder.setNegativeButton("CANCEL",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									// cancel the alert box and put a Toast to the
									// user
									dialog.cancel();
								}
							});

					AlertDialog alertDialog = alertDialogBuilder.create();
					// show alert
					alertDialog.show();
				} 

				else {
				// Internet connection is not present
				// Ask user to connect to Internet
				showAlertDialog(DM_BBM_InvoiceMenu.this,"No Internet Connection","You don't have internet connection...", false);
				}
			
			}

		});

		Button settings = (Button) findViewById(R.id.settings);
		settings.setEnabled(false);

		settings.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_Settings.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				myIntent.putExtra("TAGID", "SALES");
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button logout = (Button) findViewById(R.id.departure);
		logout.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(DM_BBM_InvoiceMenu.this,
						DM_BBM_InvoiceMainActivity.class);
				myIntent.putExtra("finish", true);
				myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_CLEAR_TASK
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
				return;
			}

		});

		Button Uploading = (Button) findViewById(R.id.uploadingData);
		Uploading.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				// get Internet status
				// checkNetwork();
				isInternetPresent = cd.isConnectingToInternet();
				if (isInternetPresent) {
					// Internet Connection is Present
					// make HTTP requests
					checkCurrentServerDB();
					try {
						AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
								DM_BBM_InvoiceMenu.this);
						// Setting Dialog Title
						alertDialogBuilder.setTitle("UPLOADING");
						// Setting Dialog Message
						alertDialogBuilder
								.setMessage("Uploading Data Server Database...");
						// set positive button: Yes message
						alertDialogBuilder.setPositiveButton("UPLOADING",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										new UploadingInvoiceDataValues()
												.execute();
										dialog.cancel();
									}
								});
						// set negative button: No message
						alertDialogBuilder.setNegativeButton("CANCEL",
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog,
											int id) {
										// cancel the alert box and put a Toast
										// to the user
										dialog.cancel();
									}
								});
						AlertDialog alertDialog = alertDialogBuilder.create();
						// show alert
						alertDialog.show();
					} catch (Exception ex) {
						ex.printStackTrace();
					}
				} else {
					// Internet connection is not present
					// Ask user to connect to Internet
					showAlertDialog(DM_BBM_InvoiceMenu.this,
							"No Internet Connection",
							"You don't have internet connection...", false);
				}

			}

			// }
		});

		Button bbmitemsmaster = (Button) findViewById(R.id.bbmitemsmaster);
		bbmitemsmaster.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_Item_Master.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		Button bbmretailermaster = (Button) findViewById(R.id.bbmretailermaster);
		bbmretailermaster.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_Retailer_Master.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});

		Button DailySalesSummery = (Button) findViewById(R.id.btnsalesSummeryReports);
		DailySalesSummery.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_Reports_Generator.class);
				myIntent.putExtra("TAGID", "0/SALES");
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}

		});

		Button bbmreceiptmain = (Button) findViewById(R.id.bbmreceipt);
		bbmreceiptmain.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent myIntent = new Intent(view.getContext(),
						DM_BBM_InvoiceSalesReceipt.class);
				myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivityForResult(myIntent, 0);
				finish();
			}
		});
	}

	// DownloadJSON AsyncTask
	private class DownloadStocks extends AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_BBM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading");
			// Set progressdialog message
			mProgressDialog.setMessage("Downloading Stock Quantity Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			// *****************Download Free Items Quentity**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItemLocFreeQty/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemLocFreeQtyResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String FreeQty = json_data.getString("FreeQty");
						String ItemCode = json_data.getString("ItemCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues insertItemFreeQty = new ContentValues();
						Cursor readItemFreeQty = null;
						try {
							readItemFreeQty = mydb.query(FITEMFREQTY_TABLE,
									null, "ItemCode ='" + ItemCode + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (readItemFreeQty != null) {
							if (readItemFreeQty.getCount() >= 1) {
								while (readItemFreeQty.moveToNext()) {
									Log.v(TAG, "Excit Free Qty (2):" + ItemCode);
									String CurrentRecordId = readItemFreeQty
											.getString(0);
									ContentValues updateStocks = new ContentValues();
									updateStocks.put("FreeQty", FreeQty.trim());
									updateStocks.put("ItemCode",ItemCode.trim());
									mydb.update(FITEMFREQTY_TABLE,
											updateStocks, "_id ='"
													+ CurrentRecordId + "'",
											null);
								}
							} else {
								Log.v(TAG, "INSERT FreeQty(2):" + i + " = "
										+ ItemCode);
								insertItemFreeQty.put("FreeQty", FreeQty.trim());
								insertItemFreeQty.put("ItemCode",ItemCode.trim());
								mydb.insert(FITEMFREQTY_TABLE, null,
										insertItemFreeQty);
								readItemFreeQty.close();
							}
						}
						readItemFreeQty.close();
						mydb.close();

					}
					arrayLength = 10;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceMenu.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("DOWNLOAD SUCCESS");
			// Setting Dialog Message
			alertDialog.setMessage("Stocks Download Completed..");
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	private class UploadingInvoiceDataValues extends
			AsyncTask<Void, Void, Void> {
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_BBM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Uploading");
			// Set progressdialog message
			mProgressDialog.setMessage("Uploading Invoice Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		@Override
		protected Void doInBackground(Void... arg0) {
			// TODO Auto-generated method stub
			mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
			// Secondry Invoice Cursors
			Cursor selectInvHeadDetails = null;
			Cursor selectInvDetailsData = null;
			Cursor selectFcompanyBranch = null;
			Cursor selectFcompanyBranchMain = null;
			Cursor selectFOrdTaxDt = null;
			Cursor selectFOrdTaxRg = null;
			Cursor selectFPRecHed = null;
			Cursor selectFPRecDet = null;

			/*********** FCompanyBranch DM Details ********************/
			try {
				/*
				 * selectFcompanyBranch = mydb.query(FCOMPANYDM_TABLE, null,
				 * "cSettingsCodedm ='SOPDA'", null, null, null, null);
				 */
				selectFcompanyBranch = mydb.query(FCOMPANYDM_TABLE, null, null,
						null, null, null, null);
			} catch (Exception e) {
			}

			if (selectFcompanyBranch != null) {
				if (selectFcompanyBranch.getCount() > 0) {
					while (selectFcompanyBranch.moveToNext()) {
						String cSettingsCodedm = selectFcompanyBranch
								.getString(1);
						String nMonth = selectFcompanyBranch.getString(2);
						String nYear = selectFcompanyBranch.getString(3);
						String nNumValdm = selectFcompanyBranch.getString(4);
						String recordid = selectFcompanyBranch.getString(5);

						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/InUpdatefCompanyDM");
						JSONStringer userJson = null;

						try {
							userJson = new JSONStringer().object()
									.key("fcdmUp").object()
									.key("cSettingsCode")
									.value(cSettingsCodedm).key("nYear")
									.value(nYear).key("nMonth").value(nMonth)
									.key("nNumVal").value(nNumValdm)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							String format1 = userJson.toString().replace(
									"\":{", "\":[{");
							String format2 = format1.replace("}", "}]}");
							Log.e("Request xxx", "Request xxx:" + format2);
							entity = new StringEntity(format2, "UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce",
											"Print Responce xxx:" + result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							Log.e("json string", "test " + json.toString()
									+ " lazım");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				} else {
					Log.v(TAG, "username :" + username);
				}
			}

			// *********** FCompanyBranch Details ********************//
			try {
				/*
				 * selectFcompanyBranchMain = mydb.query(FCOMPANYBRANCH_TABLE,
				 * null, "cSettingsCodefb ='SOPDA'", null, null, null, null);
				 */
				selectFcompanyBranchMain = mydb.query(FCOMPANYBRANCH_TABLE,
						null, null, null, null, null, null);
			} catch (Exception e) {
			}

			if (selectFcompanyBranchMain != null) {
				if (selectFcompanyBranchMain.getCount() > 0) {
					while (selectFcompanyBranchMain.moveToNext()) {
						String cSettingsCodefb = selectFcompanyBranchMain
								.getString(1);
						String BranchCode = selectFcompanyBranchMain
								.getString(2);
						String nNumValfb = selectFcompanyBranchMain
								.getString(3);
						String RecordId = selectFcompanyBranchMain.getString(4);
						String nMonthb = selectFcompanyBranchMain.getString(5);
						String nYearb = selectFcompanyBranchMain.getString(6);

						HttpPost request = new HttpPost(
								connectionURL
										+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/InUpdatefCompanyBranch");
						JSONStringer userJsonFcomB = null;
						try {
							userJsonFcomB = new JSONStringer().object()
									.key("fCBInUp").object()
									.key("cSettingsCode")
									.value(cSettingsCodefb).key("BranchCode")
									.value(BranchCode).key("nNumVal")
									.value(nNumValfb).key("nYear")
									.value(nYearb).key("nMonth").value(nMonthb)
									.key("DbName").value(currentUserServerDB)
									.endObject();
							Log.e("json", "json created");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						StringEntity entity = null;
						try {
							String format1 = userJsonFcomB.toString().replace(
									"\":{", "\":[{");
							String format2 = format1.replace("}", "}]}");
							Log.e("Request xxx", "Request xxx:" + format2);
							entity = new StringEntity(format2, "UTF-8");
						} catch (UnsupportedEncodingException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						entity.setContentEncoding(new BasicHeader(
								HTTP.CONTENT_TYPE, "application/json"));
						entity.setContentType("application/json");

						request.setEntity(entity);

						// Send request to WCF service
						DefaultHttpClient httpClient = new DefaultHttpClient();

						try {
							Log.e("response", "connect");
							HttpResponse response = httpClient.execute(request);
							// ===========================================================
							HttpEntity entitye = response.getEntity();
							is = entity.getContent();
							if (is != null) {

								try {
									BufferedReader reader = new BufferedReader(
											new InputStreamReader(is,
													"iso-8859-1"), 8);
									sb = new StringBuilder();
									sb.append(reader.readLine() + "\n");
									String line = "0";
									while ((line = reader.readLine()) != null) {
										sb.append(line + "\n");
									}
									is.close();
									String result = sb.toString();
									Log.e("String Responce",
											"Print Responce xxx:" + result);
								} catch (Exception e1) {
									e1.printStackTrace();
								}
							}
							// ==================================
							Log.e("response",
									"response get:" + response.toString());
							// System.out.println(response.toString());
							BufferedReader reader = new BufferedReader(
									new InputStreamReader(response.getEntity()
											.getContent(), "UTF-8"));
							String json = reader.readLine();
							Log.e("json string", "test " + json.toString()
									+ " lazım");
							System.out.println(json);
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
				} else {
					Log.v(TAG, "username :" + username);
				}
			}

			Cursor getRecordFInvHed = null;
			try {
				getRecordFInvHed = mydb.query(FORDHED_TABLE, null,
						"syncHed ='0' AND Active_State !='1'", null, null,
						null, null);
			} catch (Exception e) {
			}

			if (getRecordFInvHed != null) {
				if (getRecordFInvHed.getCount() > 0) {
					while (getRecordFInvHed.moveToNext()) {
						String RefNofOHedUploading = getRecordFInvHed
								.getString(1);

						// RefNofOHedUploading = "GTS/1405/0002";
						Log.v(TAG, "Array fInvHed XXXXX:" + RefNofOHedUploading);
						// **************** Select Uploading Order Details
						// ***********************//
						try {
							selectInvHeadDetails = mydb.query(FORDHED_TABLE,
									null, "RefNo ='" + RefNofOHedUploading
											+ "'", null, null, null, null);
						} catch (Exception e) {
						}
						try {
							selectInvDetailsData = mydb.query(FORDDET_TABLE,
									null, "RefNo ='" + RefNofOHedUploading
											+ "'", null, null, null, null);
						} catch (Exception e) {
						}
						// **************** Select Uploading Tax Details
						// ***********************//
						String queryChkTaxCode, queryChkTaxReg;
						try {
							queryChkTaxCode = "SELECT * from FOrdTaxDt Where RefNo = '"
									+ RefNofOHedUploading + "'";
							selectFOrdTaxDt = mydb.rawQuery(queryChkTaxCode,
									null);
						} catch (Exception e) {
							Log.v(TAG, "Save Order Tax Details Exception:" + e);
						}

						try {
							queryChkTaxReg = "SELECT * from FOrdTaxRg Where RefNo = '"
									+ RefNofOHedUploading + "'";
							selectFOrdTaxRg = mydb.rawQuery(queryChkTaxReg,
									null);
						} catch (Exception e) {
							Log.v(TAG,
									"SselectFOrdTaxRgave Order Tax Details Exception:"
											+ e);
						}
						// ********** Uploading FOrdTaxRg Header Details
						// *****************************//
						if (selectFOrdTaxRg != null) {
							if (selectFOrdTaxRg.getCount() > 0) {
								while (selectFOrdTaxRg.moveToNext()) {
									String RefNo = selectFOrdTaxRg.getString(1);
									String TaxCode = selectFOrdTaxRg
											.getString(2);
									String TaxRegNo = selectFOrdTaxRg
											.getString(3);
									try {
										JSONObject valuesJsonFOrdTaxRg = new JSONObject();
										valuesJsonFOrdTaxRg.put("RefNo", RefNo);
										valuesJsonFOrdTaxRg.put("TaxCode",
												TaxCode);
										if(TaxRegNo.trim().length() != 0){
											valuesJsonFOrdTaxRg.put("TaxRegNo",
													TaxRegNo);
										}
										else{
											valuesJsonFOrdTaxRg.put("TaxRegNo",
													" ");
										}
										
										valuesJsonFOrdTaxRg.put("DbName",
												currentUserServerDB);
										arFOrdTaxRg.add(valuesJsonFOrdTaxRg
												.toString());
									} catch (Exception e) {

									}
								}
							}
						}

						// ********** Uploading FOrdTaxDt Header Details
						// *****************************//
						if (selectFOrdTaxDt != null) {
							if (selectFOrdTaxDt.getCount() > 0) {
								while (selectFOrdTaxDt.moveToNext()) {
									String RefNo = selectFOrdTaxDt.getString(1);
									String ItemCode = selectFOrdTaxDt
											.getString(2);
									String TaxComCode = selectFOrdTaxDt
											.getString(3);
									String TaxCode = selectFOrdTaxDt
											.getString(4);
									String TaxPer = selectFOrdTaxDt
											.getString(5);
									String TaxRate = selectFOrdTaxDt
											.getString(6);
									String Taxseq = selectFOrdTaxDt
											.getString(7);
									String BTaxDetAmt = selectFOrdTaxDt
											.getString(8);
									String TaxDetAmt = selectFOrdTaxDt
											.getString(9);
									try {
										JSONObject valuesJsonFOrdTaxDt = new JSONObject();
										valuesJsonFOrdTaxDt.put("RefNo", RefNo);
										valuesJsonFOrdTaxDt.put("ItemCode",
												ItemCode);
										valuesJsonFOrdTaxDt.put("TaxComCode",
												TaxComCode);
										valuesJsonFOrdTaxDt.put("TaxCode",
												TaxCode);
										valuesJsonFOrdTaxDt.put("TaxPer",
												TaxPer);
										valuesJsonFOrdTaxDt.put("TaxRate",
												TaxRate);
										valuesJsonFOrdTaxDt.put("Taxseq",
												Taxseq);
										valuesJsonFOrdTaxDt.put("BTaxDetAmt",
												BTaxDetAmt);
										valuesJsonFOrdTaxDt.put("TaxDetAmt",
												TaxDetAmt);
										valuesJsonFOrdTaxDt.put("DbName",
												currentUserServerDB);
										arFOrdTaxDt.add(valuesJsonFOrdTaxDt
												.toString());
									} catch (Exception e) {

									}
								}
							}
						}

						// ********** Uploading Header Details
						// *****************************//
						if (selectInvHeadDetails != null) {
							if (selectInvHeadDetails.getCount() > 0) {
								while (selectInvHeadDetails.moveToNext()) {
									String RefNo = selectInvHeadDetails
											.getString(1);
									String RefNo1 = selectInvHeadDetails
											.getString(2);
									String TxnDate = selectInvHeadDetails
											.getString(3);
									try {
										date = originalFormatTxn.parse(TxnDate
												.replaceAll("[-+/.^,]", " "));
										TxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String ManuRef = selectInvHeadDetails
											.getString(4);
									String CurCode = selectInvHeadDetails
											.getString(5);
									String CostCode = selectInvHeadDetails
											.getString(6);
									String CurRate = selectInvHeadDetails
											.getString(7);
									String DebCode = selectInvHeadDetails
											.getString(8);
									String Remarks = selectInvHeadDetails
											.getString(9);
									String TxnType = selectInvHeadDetails
											.getString(10);
									String QuoTerm = selectInvHeadDetails
											.getString(11);
									String LocCode = selectInvHeadDetails
											.getString(12);
									String RepCode = selectInvHeadDetails
											.getString(13);
									String BTotalDis = selectInvHeadDetails
											.getString(14)
											.replaceAll("[,]", "");
									String TotalDis = selectInvHeadDetails
											.getString(15)
											.replaceAll("[,]", "");
									String PTotalDis = selectInvHeadDetails
											.getString(16)
											.replaceAll("[,]", "");
									String BPTotalDis = selectInvHeadDetails
											.getString(17)
											.replaceAll("[,]", "");
									String BTotalTax = selectInvHeadDetails
											.getString(18)
											.replaceAll("[,]", "");
									String TotalTax = selectInvHeadDetails
											.getString(19)
											.replaceAll("[,]", "");
									String BTotalAmt = selectInvHeadDetails
											.getString(20)
											.replaceAll("[,]", "");
									String TotalAmt = selectInvHeadDetails
											.getString(21)
											.replaceAll("[,]", "");
									String TaxReg = selectInvHeadDetails
											.getString(22);
									String Contact = selectInvHeadDetails
											.getString(23);
									String CusAdd1 = selectInvHeadDetails
											.getString(24);
									String CusAdd2 = selectInvHeadDetails
											.getString(25);
									String CusAdd3 = selectInvHeadDetails
											.getString(26);
									String CusTele = selectInvHeadDetails
											.getString(27);
									String PrtCopy = selectInvHeadDetails
											.getString(28);
									String AddUser = selectInvHeadDetails
											.getString(29);
									String AddDate = selectInvHeadDetails
											.getString(30);
									String AddMach = selectInvHeadDetails
											.getString(31);
									String disper = selectInvHeadDetails
											.getString(32)
											.replaceAll("[,]", "");
									String Appsts = selectInvHeadDetails
											.getString(33);
									String SellSts = selectInvHeadDetails
											.getString(34);
									String AppUser = selectInvHeadDetails
											.getString(35);
									String Appdate = selectInvHeadDetails
											.getString(36);
									try {
										date = originalFormat.parse(Appdate
												.replaceAll("[-+/.^,]", " "));
										Appdate = targetFormat.format(date);
									} catch (ParseException ex) {
										Appdate = "2000-01-01 12:00:00.000";
									}
									String RemarkPri = selectInvHeadDetails
											.getString(37);
									String Customer_name = selectInvHeadDetails
											.getString(38);
									String Active_State = selectInvHeadDetails
											.getString(39);
									String SalesOrd_Type = selectInvHeadDetails
											.getString(40);
									String Longitude = selectInvHeadDetails
											.getString(41);
									String Latitude = selectInvHeadDetails
											.getString(42);
									String InvStartTime = selectInvHeadDetails
											.getString(43);
									String InvEndTime = selectInvHeadDetails
											.getString(44);
									String InvHedNetTotal = selectInvHeadDetails
											.getString(45);
									String syncHed = selectInvHeadDetails
											.getString(46);
									String fsoStartTime = selectInvHeadDetails
											.getString(47);
									String salesOrdEndTime = selectInvHeadDetails
											.getString(48);

									try {
										JSONObject valuesJsonFinvHed = new JSONObject();
										valuesJsonFinvHed.put("RefNo", RefNo);
										if(RefNo1.trim().length() != 0){
											valuesJsonFinvHed.put("RefNo1",
													Contact);
										}
										else{
											valuesJsonFinvHed.put("RefNo1",
													" ");
										}
										valuesJsonFinvHed.put("TxnDate",
												TxnDate);
										if(ManuRef.trim().length() != 0){
											valuesJsonFinvHed.put("ManuRef",
													ManuRef);
										}
										else{
											valuesJsonFinvHed.put("ManuRef",
													" ");
										}
										valuesJsonFinvHed.put("CurCode",
												CurCode);
										valuesJsonFinvHed.put("CostCode",
												CostCode);
										valuesJsonFinvHed.put("CurRate",
												CurRate);
										valuesJsonFinvHed.put("DebCode",
												DebCode);
										valuesJsonFinvHed.put("Remarks",
												Remarks);
										valuesJsonFinvHed.put("TxnType",
												TxnType);
										valuesJsonFinvHed.put("QuoTerm",
												QuoTerm);
										valuesJsonFinvHed.put("LocCode",
												LocCode);
										valuesJsonFinvHed.put("RepCode",
												RepCode);
										valuesJsonFinvHed.put("BTotalDis",
												BTotalDis);
										valuesJsonFinvHed.put("TotalDis",
												TotalDis);
										valuesJsonFinvHed.put("PTotalDis",
												PTotalDis);
										valuesJsonFinvHed.put("BPTotalDis",
												BPTotalDis);
										valuesJsonFinvHed.put("BTotalTax",
												BTotalTax);
										valuesJsonFinvHed.put("TotalTax",
												TotalTax);
										valuesJsonFinvHed.put("BTotalAmt",
												BTotalAmt);
										valuesJsonFinvHed.put("TotalAmt",
												TotalAmt);
										valuesJsonFinvHed.put("TaxReg", "Y");
										
										if(Contact.trim().length() != 0){
											valuesJsonFinvHed.put("Contact",
													Contact);
										}
										else{
											valuesJsonFinvHed.put("Contact",
													" ");
										}
										
										valuesJsonFinvHed.put("CusAdd1",
												CusAdd1);
										valuesJsonFinvHed.put("CusAdd2",
												CusAdd2);
										valuesJsonFinvHed.put("CusAdd3",
												CusAdd3);
										
										if(CusTele.trim().length() != 0){
											valuesJsonFinvHed.put("CusTele",
													CusTele.replaceAll("/", ""));
										}
										else{
											valuesJsonFinvHed.put("CusTele",
													" ");
										}
										
										
										valuesJsonFinvHed.put("PrtCopy",
												PrtCopy);
										valuesJsonFinvHed.put("AddUser",
												AddUser);
										valuesJsonFinvHed.put("AddDate",
												AddDate);
										valuesJsonFinvHed.put("AddMach",
												AddMach);
										valuesJsonFinvHed.put("disper", disper);
										valuesJsonFinvHed.put("Appsts", Appsts);
										valuesJsonFinvHed.put("SellSts",
												SellSts);
										
										if(AppUser.trim().length() != 0){
											valuesJsonFinvHed.put("AppUser",
													AppUser);
										}
										else{
											valuesJsonFinvHed.put("AppUser",
													" ");
										}
										valuesJsonFinvHed.put("Appdate",
												Appdate);
										valuesJsonFinvHed.put("RemarkPri",
												RemarkPri);
										valuesJsonFinvHed.put("fsoStartTime",
												fsoStartTime);
										valuesJsonFinvHed.put("fsoEndTime",
												salesOrdEndTime);
										valuesJsonFinvHed.put("DbName",
												currentUserServerDB);
										arFinvHed.add(valuesJsonFinvHed
												.toString());
									} catch (Exception ex) {
										ex.printStackTrace();
									}
								}
							}
						}

						if (selectInvDetailsData != null) {
							if (selectInvDetailsData.getCount() > 0) {
								while (selectInvDetailsData.moveToNext()) {
									String orddet_id = selectInvDetailsData
											.getString(0);
									String RefNo = selectInvDetailsData
											.getString(1);
									String TxnDate = selectInvDetailsData
											.getString(2);
									try {
										date = originalFormatTxn.parse(TxnDate
												.replaceAll("[-+/.^,]", " "));
										TxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String TxnType = selectInvDetailsData
											.getString(3);
									String SeqNo = selectInvDetailsData
											.getString(4);
									String Itemcode = selectInvDetailsData
											.getString(5);
									String Qty = selectInvDetailsData
											.getString(6);
									String BalQty = selectInvDetailsData
											.getString(7);
									String TaxComCode = selectInvDetailsData
											.getString(8);
									String BSellPrice = selectInvDetailsData
											.getString(9).replaceAll("[,]", "");
									String SellPrice = selectInvDetailsData
											.getString(10)
											.replaceAll("[,]", "");
									String BTSellPrice = selectInvDetailsData
											.getString(11)
											.replaceAll("[,]", "");
									String TSellPrice = selectInvDetailsData
											.getString(12)
											.replaceAll("[,]", "");
									String PrilCode = selectInvDetailsData
											.getString(13)
											.replaceAll("[,]", "");
									Log.v(TAG, "Exception 1:" + RefNo + "/"
											+ TxnDate + "/" + TxnType + "/"
											+ SeqNo + "/" + Itemcode + "/"
											+ Qty + "/" + BalQty + "/"
											+ TaxComCode + "/" + BSellPrice
											+ "/" + PrilCode);
									String DisPer = selectInvDetailsData
											.getString(14)
											.replaceAll("[,]", "");
									String BDisAmt = selectInvDetailsData
											.getString(15)
											.replaceAll("[,]", "");
									String DisAmt = selectInvDetailsData
											.getString(16)
											.replaceAll("[,]", "");
									String PDisAmt = selectInvDetailsData
											.getString(17)
											.replaceAll("[,]", "");
									String BPDisAmt = selectInvDetailsData
											.getString(18)
											.replaceAll("[,]", "");
									String BTaxAmt = selectInvDetailsData
											.getString(19)
											.replaceAll("[,]", "");
									String TaxAmt = selectInvDetailsData
											.getString(20)
											.replaceAll("[,]", "");
									String BAmt = selectInvDetailsData
											.getString(21)
											.replaceAll("[,]", "");
									String Amt = selectInvDetailsData
											.getString(22)
											.replaceAll("[,]", "");
									String Linkrec = selectInvDetailsData
											.getString(23);
									String OrSellPrice = selectInvDetailsData
											.getString(24)
											.replaceAll("[,]", "");
									String OrBSellPrice = selectInvDetailsData
											.getString(25)
											.replaceAll("[,]", "");
									String OrTSellPrice = selectInvDetailsData
											.getString(26)
											.replaceAll("[,]", "");
									String OrBTSellPrice = selectInvDetailsData
											.getString(27)
											.replaceAll("[,]", "");
									String Packing = selectInvDetailsData
											.getString(28);
									Log.v(TAG, "Exception 2:" + DisPer + "/"
											+ BDisAmt + "/" + DisAmt + "/"
											+ PDisAmt + "/" + BPDisAmt + "/"
											+ TaxAmt + "/" + BTaxAmt + "/"
											+ BAmt + "/" + Amt + "/" + Linkrec);
									Log.v(TAG, "Exception 3:" + OrSellPrice
											+ "/" + OrBSellPrice + "/"
											+ OrTSellPrice + "/"
											+ OrBTSellPrice);
									String Quopacking = selectInvDetailsData
											.getString(29);
									String cases = selectInvDetailsData
											.getString(30);
									String freeqty = selectInvDetailsData
											.getString(31)
											.replaceAll("[,]", "");
									String balfreeqty = selectInvDetailsData
											.getString(32)
											.replaceAll("[,]", "");
									String ItemName = selectInvDetailsData
											.getString(33);
									String RetailPrice = selectInvDetailsData
											.getString(34)
											.replaceAll("[,]", "");
									String BrandCode = selectInvDetailsData
											.getString(35);
									String BrandName = selectInvDetailsData
											.getString(36);
									String value = selectInvDetailsData
											.getString(37);
									String totordval = selectInvDetailsData
											.getString(38);
									String finalQty = selectInvDetailsData
											.getString(39);
									String syncDet = selectInvDetailsData
											.getString(40);
									Log.v(TAG, "Exception 4:" + Quopacking
											+ "/" + cases + "/" + freeqty + "/"
											+ balfreeqty + "/" + ItemName);

									try {
										JSONObject valuesJsonFinvDet = new JSONObject();
										valuesJsonFinvDet.put("RefNo", RefNo);
										valuesJsonFinvDet.put("TxnDate",
												TxnDate);
										valuesJsonFinvDet.put("TxnType",
												TxnType);
										valuesJsonFinvDet.put("SeqNo", SeqNo);
										valuesJsonFinvDet.put("Itemcode",
												Itemcode);
										valuesJsonFinvDet.put("Qty", Qty);
										valuesJsonFinvDet.put("BalQty", BalQty);
										valuesJsonFinvDet.put("TaxComCode",
												TaxComCode);
										valuesJsonFinvDet.put("BSellPrice",
												BSellPrice);
										valuesJsonFinvDet.put("SellPrice",
												SellPrice);
										valuesJsonFinvDet.put("BTSellPrice",
												BTSellPrice);
										valuesJsonFinvDet.put("TSellPrice",
												TSellPrice);
										valuesJsonFinvDet.put("PrilCode",
												PrilCode);
										valuesJsonFinvDet.put("DisPer", DisPer);
										valuesJsonFinvDet.put("BDisAmt",
												BDisAmt);
										valuesJsonFinvDet.put("DisAmt", DisAmt);
										valuesJsonFinvDet.put("PDisAmt",
												PDisAmt);
										valuesJsonFinvDet.put("BPDisAmt",
												BPDisAmt);
										valuesJsonFinvDet.put("BTaxAmt",
												BTaxAmt);
										valuesJsonFinvDet.put("TaxAmt", TaxAmt);
										valuesJsonFinvDet.put("BAmt", BAmt);
										valuesJsonFinvDet.put("Amt", Amt);
										valuesJsonFinvDet.put("Linkrec",
												Linkrec);
										valuesJsonFinvDet.put("RecordId",
												orddet_id);
										valuesJsonFinvDet.put("OrSellPrice",
												OrSellPrice);
										valuesJsonFinvDet.put("OrBSellPrice",
												OrBSellPrice);
										valuesJsonFinvDet.put("OrTSellPrice",
												OrTSellPrice);
										valuesJsonFinvDet.put("OrBTSellPrice",
												OrBTSellPrice);
										valuesJsonFinvDet.put("Packing",
												Packing);
										
										if(Quopacking.trim().length() != 0){
											valuesJsonFinvDet.put("Quopacking",
													Quopacking);
										}
										else{
											valuesJsonFinvDet.put("Quopacking",
													" ");
										}
										valuesJsonFinvDet.put("cases", cases);
										valuesJsonFinvDet.put("freeqty",
												freeqty);
										valuesJsonFinvDet.put("balfreeqty",
												balfreeqty);
										valuesJsonFinvDet.put("ItemName",
												ItemName);
										valuesJsonFinvDet.put("RetailPrice",
												RetailPrice);
										valuesJsonFinvDet.put("DbName",
												currentUserServerDB);
										arFinvDet.add(valuesJsonFinvDet
												.toString());
									} catch (Exception ex) {
										Log.v(TAG, "Exception" + ex);
									}
								}
							}
						}

						// ********** Upload TaxDetails ***************//

						// Uploading
						// arFOrdTaxRg/arFOrdTaxDt/arFinvHed/arFinvDet
						String strFH = arFinvHed.toString();
						String strFD = arFinvDet.toString();
						String strOrdTaxReg = arFOrdTaxRg.toString();
						String strOrdTaxDet = arFOrdTaxDt.toString();

						if (selectInvHeadDetails.getCount() <= 0) {
							Log.v(TAG, "ARRAY 1" + strFH + "/" + strFD);
						} else {
							strFH = strFH.replace("[", "");
							strFH = strFH.replace("]", "");
							strFD = strFD.replace("[", "");
							strFD = strFD.replace("]", "");
							strOrdTaxReg = strOrdTaxReg.replace("[", "");
							strOrdTaxReg = strOrdTaxReg.replace("]", "");
							strOrdTaxDet = strOrdTaxDet.replace("[", "");
							strOrdTaxDet = strOrdTaxDet.replace("]", "");

							// PDADBWebServiceM
							HttpPost request = new HttpPost(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/updateFOrdHed");
							JSONStringer userJson = null;
							try {
								userJson = new JSONStringer().object()
										.key("fOHed").value(strFH).key("fODet")
										.value(strFD).key("fOTaxDt")
										.value(strOrdTaxDet).key("fOTaxRg")
										.value(strOrdTaxReg);
							} catch (Exception e) {
							}

							StringEntity entity = null;
							try {
								// String repval = userJson.toString() + "}" +
								// ",UTF-8";
								String format1 = userJson.toString().replace(
										"[", "");
								String format2 = format1.replace("]", "");
								String format3 = format2.replace("\\", "");

								String format4 = "\"fOHed\":\"";
								String format5 = "\",\"fODet\":\"";
								String format5a = "\",\"fOTaxDt\":\"";
								String format5b = "\",\"fOTaxRg\":\"";

								String format6 = format3.replace(format4,
										"\"fOHed\":[");
								String format7 = format6.replace(format5,
										"],\"fODet\":[");
								String format8 = format7.replace(format5a,
										"],\"fOTaxDt\":[");
								String format9 = format8.replace(format5b,
										"],\"fOTaxRg\":[");

								format9 = format9 + "}";
								String dj = format9.replace("\"}\"}", "\"}]}");

								Log.v(TAG,
										"****************************************\n");
								Log.v(TAG, "JSON - Request: =" + dj);

								entity = new StringEntity(dj, "UTF-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							entity.setContentEncoding(new BasicHeader(
									HTTP.CONTENT_TYPE, "application/json"));
							entity.setContentType("application/json");
							request.setEntity(entity);

							// Send request to WCF service
							DefaultHttpClient httpClient = new DefaultHttpClient();

							try {
								Log.e("response", "connect");
								HttpResponse response = httpClient
										.execute(request);
								// Log.e("RES DJ1:", "RES DJ1:" +
								// response.toString());
								// ===========================================================
								HttpEntity entitye = response.getEntity();
								is = entitye.getContent();
								if (is != null) {
									int resval = 200;
									try {
										BufferedReader reader = new BufferedReader(
												new InputStreamReader(is,
														"iso-8859-1"), 8);
										sb = new StringBuilder();
										sb.append(reader.readLine() + "\n");
										String line = "0";
										while ((line = reader.readLine()) != null) {
											sb.append(line + "\n");
										}
										is.close();
										String result = sb.toString();
										Log.v(TAG, "CHKQUERY: =" + result);
										String result1 = result.replace("\"",
												"");
										// int result1Val =
										// Integer.parseInt(result1.trim());

										if (result1.trim().equals("200")) {
											Log.e("RES DJ3:", "RESULT 200 P1:"
													+ result1);
											ContentValues finvhedSynUpdateVal = new ContentValues();
											finvhedSynUpdateVal.put("syncHed",
													"1");
											mydb.update(
													FORDHED_TABLE,
													finvhedSynUpdateVal,
													"syncHed ='0' AND Active_State !='1'",
													null);
											ContentValues finvdetSynUpdateVal = new ContentValues();
											finvdetSynUpdateVal.put("syncDet",
													"1");
											mydb.update(FORDDET_TABLE,
													finvdetSynUpdateVal,
													"syncDet ='0'", null);
											String fInvHedCountStr = Integer
													.toString(fInvHedCount);
											SIupSummary = "(SI -"
													+ fInvHedCountStr + "/"
													+ fInvHedCountStr + ")";
										} else if (result1.trim()
												.equals("null")) {
											Log.e("RES DJ2:",
													"RESULT ELSE NULL");
										}

										else {
											Log.v(TAG, "Responce XXXX :"
													+ result);
											String result12 = result.replace(
													"\",", "");
											String result13 = result12.replace(
													"\"", "");
											String result14 = result13.replace(
													"\\", "");
											String result15 = result14.replace(
													"200,", "");
											String[] items = result15
													.split(",");
											List<String> container = Arrays
													.asList(items);
											List<String> android = new ArrayList<String>(
													container);
											Log.e("RES DJ2:",
													"RESULT ELSE 200 :"
															+ android);
											// Getting Iterator from List
											Iterator<String> iteratorSI = android
													.iterator();
											try {
												selectInvHeadDetailsReChk = mydb
														.query(FORDHED_TABLE,
																null,
																"syncHed ='0' AND Active_State !='1'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectInvDetailsDataReChk = mydb
														.query(FORDDET_TABLE,
																null,
																"syncDet ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											int i = 1;
											while (iteratorSI.hasNext()) {

												ReadRefErrorUpload = iteratorSI
														.next();

												try {
													Log.e("RES DJ2:",
															"SYNC FAIL HED 7 :"
																	+ ReadRefErrorUpload);
													selectInvHeadDetailsReChk = mydb
															.query(FORDHED_TABLE,
																	null,
																	"RefNo ='"
																			+ ReadRefErrorUpload
																					.trim()
																			+ "' AND Active_State !='1'",
																	null, null,
																	null, null);
												} catch (Exception e) {
												}
												try {
													Log.e("RES DJ2:",
															"SYNC FAIL DET 7 :"
																	+ ReadRefErrorUpload);
													selectInvDetailsDataReChk = mydb
															.query(FORDDET_TABLE,
																	null,
																	"RefNo ='"
																			+ ReadRefErrorUpload
																					.trim()
																			+ "'",
																	null, null,
																	null, null);
												} catch (Exception e) {
												}

												Log.e("RES DJ2:",
														"CHK HED:"
																+ selectInvHeadDetailsReChk
																		.getCount()
																+ " = " + i);
												Log.e("RES DJ2:",
														"CHK DET:"
																+ selectInvDetailsDataReChk
																		.getCount()
																+ " = " + i);

												if (selectInvHeadDetailsReChk != null) {
													if (selectInvHeadDetailsReChk
															.getCount() > 0) {
														while (selectInvHeadDetailsReChk
																.moveToNext()) {
															String syncUpdateHedSI = selectInvHeadDetailsReChk
																	.getString(1);
															ContentValues finvHedSynUpdaterall = new ContentValues();
															Log.e("RES DJ2:",
																	"SYNC FAIL 7 UPDATE HED:"
																			+ syncUpdateHedSI);
															finvHedSynUpdaterall
																	.put("syncHed",
																			"7");
															mydb.update(
																	FORDHED_TABLE,
																	finvHedSynUpdaterall,
																	"RefNo ='"
																			+ syncUpdateHedSI
																			+ "' AND Active_State !='1'",
																	null);
														}
													}
													// selectInvHeadDetailsReChk.close();
												}

												if (selectInvDetailsDataReChk != null) {
													if (selectInvDetailsDataReChk
															.getCount() > 0) {
														while (selectInvDetailsDataReChk
																.moveToNext()) {
															String syncUpdateDetSI = selectInvDetailsDataReChk
																	.getString(1);
															ContentValues finvdetSynUpdaterall = new ContentValues();
															Log.e("RES DJ2:",
																	"SYNC FAIL 7 UPDATE DET:"
																			+ syncUpdateDetSI);
															finvdetSynUpdaterall
																	.put("syncDet",
																			"7");
															mydb.update(
																	FORDDET_TABLE,
																	finvdetSynUpdaterall,
																	"RefNo ='"
																			+ syncUpdateDetSI
																			+ "'",
																	null);
														}
													}
													// selectInvHeadDetailsReChk.close();
												}
												i = i + 1;
												fInvHedCountFail = fInvHedCountFail + 1;
												String fInvHedCountStr = Integer
														.toString(fInvHedCount);
												int uploadSuccess = fInvHedCount
														- fInvHedCountFail;
												String fInvHedCountStrFail = Integer
														.toString(fInvHedCountFail);
												String fInvHedCountStrSuccess = Integer
														.toString(uploadSuccess);

												SIupSummary = "(SI -"
														+ fInvHedCountStrSuccess
														+ "/" + fInvHedCountStr
														+ ")";
												// iteratorSI.next();
											}

											iteratorSI.remove();
											try {
												selectInvHeadDetailsUpdate = mydb
														.query(FORDHED_TABLE,
																null,
																"syncHed ='0' AND Active_State !='1'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectInvDetailsDataUpdate = mydb
														.query(FORDDET_TABLE,
																null,
																"syncDet ='0'",
																null, null,
																null, null);
											} catch (Exception e) {
											}

											if (selectInvHeadDetailsUpdate != null) {
												if (selectInvHeadDetailsUpdate
														.getCount() > 0) {
													while (selectInvHeadDetailsUpdate
															.moveToNext()) {
														String mainRefNoHed = selectInvHeadDetailsUpdate
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC OK HED :"
																		+ mainRefNoHed);
														ContentValues finvhedSynUpdaterall = new ContentValues();
														finvhedSynUpdaterall
																.put("syncHed",
																		"1");
														mydb.update(
																FORDHED_TABLE,
																finvhedSynUpdaterall,
																"RefNo ='"
																		+ mainRefNoHed
																		+ "' AND Active_State !='1'",
																null);
													}
												}
											}
											if (selectInvDetailsDataUpdate != null) {
												if (selectInvDetailsDataUpdate
														.getCount() > 0) {
													while (selectInvDetailsDataUpdate
															.moveToNext()) {
														String mainRefNoDet = selectInvDetailsDataUpdate
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC OK DET :"
																		+ mainRefNoDet);
														ContentValues finvdetSynUpdaterall = new ContentValues();
														finvdetSynUpdaterall
																.put("syncDet",
																		"1");
														mydb.update(
																FORDDET_TABLE,
																finvdetSynUpdaterall,
																"RefNo ='"
																		+ mainRefNoDet
																		+ "'",
																null);
													}
												}
											}

											try {
												selectInvHeadDetailsChkFail = mydb
														.query(FORDHED_TABLE,
																null,
																"syncHed ='7' AND Active_State !='1'",
																null, null,
																null, null);
											} catch (Exception e) {
											}
											try {
												selectInvDetailsDataChkFail = mydb
														.query(FORDDET_TABLE,
																null,
																"syncDet ='7'",
																null, null,
																null, null);
											} catch (Exception e) {
											}

											if (selectInvHeadDetailsChkFail != null) {
												if (selectInvHeadDetailsChkFail
														.getCount() > 0) {
													while (selectInvHeadDetailsChkFail
															.moveToNext()) {

														String mainRefNoHedFail = selectInvHeadDetailsChkFail
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC FAIL UPDATE HED :"
																		+ mainRefNoHedFail);
														ContentValues finvhedSynUpdaterallFail = new ContentValues();
														finvhedSynUpdaterallFail
																.put("syncHed",
																		"0");
														mydb.update(
																FORDHED_TABLE,
																finvhedSynUpdaterallFail,
																"RefNo ='"
																		+ mainRefNoHedFail
																		+ "' AND Active_State !='1'",
																null);
													}
												}
											}
											if (selectInvDetailsDataChkFail != null) {
												if (selectInvDetailsDataChkFail
														.getCount() > 0) {
													while (selectInvDetailsDataChkFail
															.moveToNext()) {
														String mainRefNoDetFail = selectInvDetailsDataChkFail
																.getString(1);
														Log.e("RES DJ2:",
																"SYNC FAIL UPDATE DET :"
																		+ mainRefNoDetFail);
														ContentValues finvdetSynUpdaterallFail = new ContentValues();
														finvdetSynUpdaterallFail
																.put("syncDet",
																		"0");
														mydb.update(
																FORDDET_TABLE,
																finvdetSynUpdaterallFail,
																"RefNo ='"
																		+ mainRefNoDetFail
																		+ "'",
																null);
													}
												}
											}
										}

									} catch (Exception e1) {
										e1.printStackTrace();
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
							arFinvHed.clear();
							arFinvDet.clear();
						}

					}
				}
			}

			/***************** Receipt Uploading ***************/

			Cursor getRecordFPRecHed = null;
			try {
				getRecordFPRecHed = mydb.query(FPRECHED_TABLE, null,
						"SyncState ='0' AND ActiveState !='1'", null, null,
						null, null);
			} catch (Exception e) {
			}

			if (getRecordFPRecHed != null) {
				if (getRecordFPRecHed.getCount() > 0) {
					while (getRecordFPRecHed.moveToNext()) {
						String RefNoFPRecHed = getRecordFPRecHed.getString(1);

						try {
							selectFPRecHed = mydb.query(FPRECHED_TABLE, null,
									"RefNo ='" + RefNoFPRecHed + "'", null,
									null, null, null);
						} catch (Exception e) {
						}

						try {
							selectFPRecDet = mydb.query(FPRECDET_TABLE, null,
									"RefNo ='" + RefNoFPRecHed + "'", null,
									null, null, null);
						} catch (Exception e) {
						}

						/********** Uploading FPRECHED_TABLE Details **********/
						if (selectFPRecHed != null) {
							if (selectFPRecHed.getCount() > 0) {
								while (selectFPRecHed.moveToNext()) {
									String RefNo = selectFPRecHed.getString(1);
									String ManuRef = selectFPRecHed
											.getString(2);
									String SaleRefNo = selectFPRecHed
											.getString(3);
									String RepCode = selectFPRecHed
											.getString(4);
									String TxnType = selectFPRecHed
											.getString(5);
									String Chqno = selectFPRecHed.getString(6);
									String ChqDate = selectFPRecHed
											.getString(7);
									try {
										date = originalFormatTxn.parse(ChqDate
												.replaceAll("[-+/.^,]", " "));
										ChqDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										ChqDate = "1900-01-01";
									}
									String TxnDate = selectFPRecHed
											.getString(8);
									try {
										date = originalFormatTxn.parse(TxnDate
												.replaceAll("[-+/.^,]", " "));
										TxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String CurCode = selectFPRecHed
											.getString(9);
									String CurRate1 = selectFPRecHed
											.getString(10);
									String DebCode = selectFPRecHed
											.getString(11);
									String TotalAmt = selectFPRecHed
											.getString(12);
									String BTotalAmt = selectFPRecHed
											.getString(13);
									String BankCur = selectFPRecHed
											.getString(14);
									String BankRate = selectFPRecHed
											.getString(15);
									String BankAmt = selectFPRecHed
											.getString(16);
									String BankCharge = selectFPRecHed
											.getString(17);
									String BBankChg = selectFPRecHed
											.getString(18);
									String GnLsCal = selectFPRecHed
											.getString(19);
									String DbAcc = selectFPRecHed.getString(20);
									String PayType = selectFPRecHed
											.getString(21);
									String PrtCopy = selectFPRecHed
											.getString(22);
									String GlPost = selectFPRecHed
											.getString(23);
									String Remarks = selectFPRecHed
											.getString(24);
									String CardSlipNo = selectFPRecHed
											.getString(25);
									String ExpDate = selectFPRecHed
											.getString(26);
									try {
										date = originalFormatTxn.parse(ExpDate
												.replaceAll("[-+/.^,]", " "));
										ExpDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										ExpDate = "1900-01-01";
									}
									String CrdTypCode = selectFPRecHed
											.getString(27);
									String CCBankAmt = selectFPRecHed
											.getString(28);
									String GlBatch = selectFPRecHed
											.getString(29);
									String AddUser = selectFPRecHed
											.getString(30);
									String AddMach = selectFPRecHed
											.getString(31);
									String AddDate = selectFPRecHed
											.getString(32);
									String CurRate = selectFPRecHed
											.getString(33);

									try {
										JSONObject valuesJsonFPRecHed = new JSONObject();
										valuesJsonFPRecHed.put("RefNo", RefNo);

										if (ManuRef.trim().length() != 0) {
											valuesJsonFPRecHed.put("ManuRef",
													ManuRef);
										} else {
											valuesJsonFPRecHed.put("ManuRef",
													" ");
										}

										if (SaleRefNo.trim().length() != 0) {
											valuesJsonFPRecHed.put("SaleRefNo",
													SaleRefNo);
										} else {
											valuesJsonFPRecHed.put("SaleRefNo",
													" ");
										}

										valuesJsonFPRecHed.put("RepCode",
												RepCode);
										valuesJsonFPRecHed.put("TxnType",
												TxnType);
										if (Chqno.trim().trim().length() != 0) {
											valuesJsonFPRecHed.put("Chqno",
													Chqno);
										} else {
											valuesJsonFPRecHed
													.put("Chqno", " ");
										}
										if (ChqDate.trim().length() != 0) {
											valuesJsonFPRecHed.put("ChqDate",
													ChqDate);
										} else {
											valuesJsonFPRecHed.put("ChqDate",
													" ");
										}

										Log.v(TAG, "ManuRef    : " + ManuRef);
										Log.v(TAG, "SaleRefNo  : " + SaleRefNo);
										Log.v(TAG, "Chqno      : " + Chqno);
										Log.v(TAG, "ChqDate    : " + ChqDate);

										valuesJsonFPRecHed.put("TxnDate",
												TxnDate);
										valuesJsonFPRecHed.put("CurCode",
												CurCode);
										valuesJsonFPRecHed.put("CurRate1",
												CurRate1);
										valuesJsonFPRecHed.put("DebCode",
												DebCode);
										if (TotalAmt.trim().length() != 0) {
											valuesJsonFPRecHed.put("TotalAmt",
													TotalAmt);
										} else {
											valuesJsonFPRecHed.put("TotalAmt",
													"0.00");
										}
										if (BTotalAmt.trim().length() != 0) {
											valuesJsonFPRecHed.put("BTotalAmt",
													BTotalAmt);
										} else {
											valuesJsonFPRecHed.put("BTotalAmt",
													"0.00");
										}
										if (BankCur.trim().length() != 0) {
											valuesJsonFPRecHed.put("BankCur",
													BankCur);
										} else {
											valuesJsonFPRecHed.put("BankCur",
													" ");
										}
										if (BankRate.trim().length() != 0) {
											valuesJsonFPRecHed.put("BankRate",
													BankRate);
										} else {
											valuesJsonFPRecHed.put("BankRate",
													" ");
										}
										if (BankAmt.trim().length() != 0) {
											valuesJsonFPRecHed.put("BankAmt",
													BankAmt);
										} else {
											valuesJsonFPRecHed.put("BankAmt",
													"0.00");
										}
										if (BankCharge.trim().length() != 0) {
											valuesJsonFPRecHed.put(
													"BankCharge", BankCharge);
										} else {
											valuesJsonFPRecHed.put(
													"BankCharge", "0.00");
										}
										if (BBankChg.trim().length() != 0) {
											valuesJsonFPRecHed.put("BBankChg",
													BBankChg);
										} else {
											valuesJsonFPRecHed.put("BBankChg",
													"0.00");
										}
										if (GnLsCal.trim().length() != 0) {
											valuesJsonFPRecHed.put("GnLsCal",
													GnLsCal);
										} else {
											valuesJsonFPRecHed.put("GnLsCal",
													" ");
										}
										if (DbAcc.trim().length() != 0) {
											valuesJsonFPRecHed.put("DbAcc",
													DbAcc);
										} else {
											valuesJsonFPRecHed
													.put("DbAcc", " ");
										}

										valuesJsonFPRecHed.put("PayType",
												PayType);
										valuesJsonFPRecHed.put("PrtCopy",
												PrtCopy);
										if (GlPost.length() != 0) {
											valuesJsonFPRecHed.put("GlPost",
													GlPost);
										} else {
											valuesJsonFPRecHed.put("GlPost",
													" ");
										}
										if (Remarks.trim().length() != 0) {
											valuesJsonFPRecHed.put("Remarks",
													Remarks);
										} else {
											valuesJsonFPRecHed.put("Remarks",
													" ");
										}
										if (CardSlipNo.trim().length() != 0) {
											valuesJsonFPRecHed.put(
													"CardSlipNo", " ");
										} else {
											valuesJsonFPRecHed.put(
													"CardSlipNo", " ");
										}
										if (ExpDate.trim().length() != 0) {
											valuesJsonFPRecHed.put("ExpDate",
													"2014-06-19 04:59:45.056");
										} else {
											valuesJsonFPRecHed.put("ExpDate",
													"2014-06-19 04:59:45.056");
										}
										if (CrdTypCode.trim().length() != 0) {
											valuesJsonFPRecHed.put(
													"CrdTypCode", " ");
										} else {
											valuesJsonFPRecHed.put(
													"CrdTypCode", " ");
										}
										if (CCBankAmt.trim().length() != 0) {
											valuesJsonFPRecHed.put("CCBankAmt",
													"0.00");
										} else {
											valuesJsonFPRecHed.put("CCBankAmt",
													"0.00");
										}
										if (CCBankAmt.trim().length() != 0) {
											valuesJsonFPRecHed.put("GlBatch",
													" ");
										} else {
											valuesJsonFPRecHed.put("GlBatch",
													" ");
										}
										valuesJsonFPRecHed.put("AddUser",
												AddUser);
										valuesJsonFPRecHed.put("AddMach",
												AddMach);
										valuesJsonFPRecHed.put("AddDate",
												AddDate);
										valuesJsonFPRecHed.put("CurRate",
												CurRate);
										valuesJsonFPRecHed.put("DbName",
												currentUserServerDB);
										arFPRecHed.add(valuesJsonFPRecHed
												.toString());
									} catch (Exception ex) {
										Log.v(TAG, "Exception" + ex);
									}
								}
							}
						}

						/********** Uploading FPRECDET_TABLE Details **********/

						if (selectFPRecDet != null) {
							if (selectFPRecDet.getCount() > 0) {
								while (selectFPRecDet.moveToNext()) {
									String RefNo = selectFPRecDet.getString(1);
									String RefNo1 = selectFPRecDet.getString(2);
									String SaleRefNo = selectFPRecDet
											.getString(3);
									String ManuRef = selectFPRecDet
											.getString(4);
									String TxnType = selectFPRecDet
											.getString(5);
									String TxnDate = selectFPRecDet
											.getString(6);
									try {
										date = originalFormatTxn.parse(TxnDate
												.replaceAll("[-+/.^,]", " "));
										TxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										TxnDate = "1900-01-01";
									}
									String DtxnDate = selectFPRecDet
											.getString(7);
									try {
										date = originalFormatTxn.parse(DtxnDate
												.replaceAll("[-+/.^,]", " "));
										DtxnDate = targetFormatTxn.format(date);
									} catch (ParseException ex) {
										DtxnDate = "1900-01-01";
									}
									String DtxnType = selectFPRecDet
											.getString(8);
									String DCurCode = selectFPRecDet
											.getString(9);
									String DCurRate = selectFPRecDet
											.getString(10);
									String OCurRate = selectFPRecDet
											.getString(11);
									String RepCode = selectFPRecDet
											.getString(12);
									String Amt = selectFPRecDet.getString(13);
									String BAmt = selectFPRecDet.getString(14);
									String GainLosAmt = selectFPRecDet
											.getString(15);
									String BnkChgs = selectFPRecDet
											.getString(16);
									String BBnkChgs = selectFPRecDet
											.getString(17);
									String AloAmt = selectFPRecDet
											.getString(18);
									String OvPayAmt = selectFPRecDet
											.getString(19);
									String OvPayBal = selectFPRecDet
											.getString(20);

									try {
										JSONObject valuesJsonFPRecDet = new JSONObject();
										valuesJsonFPRecDet.put("RefNo", RefNo);
										valuesJsonFPRecDet
												.put("RefNo1", RefNo1);
										valuesJsonFPRecDet.put("SaleRefNo",
												SaleRefNo);
										valuesJsonFPRecDet.put("ManuRef",
												ManuRef);
										valuesJsonFPRecDet.put("TxnType",
												TxnType);
										valuesJsonFPRecDet.put("TxnDate",
												TxnDate);
										valuesJsonFPRecDet.put("DtxnDate",
												DtxnDate);
										valuesJsonFPRecDet.put("DtxnType",
												DtxnType);
										valuesJsonFPRecDet.put("DCurCode",
												DCurCode);
										valuesJsonFPRecDet.put("DCurRate",
												DCurRate);
										valuesJsonFPRecDet.put("OCurRate",
												OCurRate);
										valuesJsonFPRecDet.put("RepCode",
												RepCode);
										valuesJsonFPRecDet.put("Amt", Amt);
										valuesJsonFPRecDet.put("BAmt", BAmt);
										valuesJsonFPRecDet.put("GainLosAmt",
												GainLosAmt);
										valuesJsonFPRecDet.put("BnkChgs",
												BnkChgs);
										valuesJsonFPRecDet.put("BBnkChgs",
												BBnkChgs);
										valuesJsonFPRecDet
												.put("AloAmt", AloAmt);
										valuesJsonFPRecDet.put("OvPayAmt",
												OvPayAmt);
										valuesJsonFPRecDet.put("OvPayBal",
												OvPayBal);
										valuesJsonFPRecDet.put("DbName",
												currentUserServerDB);
										arFPRecDet.add(valuesJsonFPRecDet
												.toString());
									} catch (Exception ex) {
										Log.v(TAG, "Exception" + ex);
									}

								}
							}
						}

						String strRECHED = arFPRecHed.toString();
						String strRECDET = arFPRecDet.toString();

						if (getRecordFPRecHed.getCount() <= 0) {
							Log.v(TAG, "ARRAY 1" + strRECHED + "/" + strRECDET);
						} else {
							strRECHED = strRECHED.replace("[", "");
							strRECHED = strRECHED.replace("]", "");
							strRECDET = strRECDET.replace("[", "");
							strRECDET = strRECDET.replace("]", "");
							JSONStringer userJson = null;

							// PDADBWebServiceM
							HttpPost request = new HttpPost(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/insertfPRecHed");

							try {
								userJson = new JSONStringer().object()
										.key("fHed").value(strRECHED)
										.key("fDet").value(strRECDET);
							} catch (Exception e) {
							}

							StringEntity entity = null;
							try {
								String format1 = userJson.toString().replace(
										"[", "");
								String format2 = format1.replace("]", "");
								String format3 = format2.replace("\\", "");
								String format4 = "\"fHed\":\"";
								String format5 = "\",\"fDet\":\"";
								String format6 = format3.replace(format4,
										"\"fHed\":[");
								String format7 = format6.replace(format5,
										"],\"fDet\":[");
								format7 = format7 + "}";
								String dj = format7.replace("\"}\"}", "\"}]}");
								Log.v(TAG,
										"****************************************\n");
								Log.v(TAG, "JSON - Request: =" + dj);
								entity = new StringEntity(dj, "UTF-8");
							} catch (Exception e) {
							}

							entity.setContentEncoding(new BasicHeader(
									HTTP.CONTENT_TYPE, "application/json"));
							entity.setContentType("application/json");
							request.setEntity(entity);

							// Send request to WCF service
							DefaultHttpClient httpClient = new DefaultHttpClient();

							try {
								Log.e("response", "connect");
								HttpResponse response = httpClient
										.execute(request);
								HttpEntity entitye = response.getEntity();
								is = entitye.getContent();
								if (is != null) {
									int resval = 200;
									try {
										BufferedReader reader = new BufferedReader(
												new InputStreamReader(is,
														"iso-8859-1"), 8);
										sb = new StringBuilder();
										sb.append(reader.readLine() + "\n");
										String line = "0";
										while ((line = reader.readLine()) != null) {
											sb.append(line + "\n");
										}
										is.close();
										String result = sb.toString();
										Log.v(TAG, "CHKQUERY: =" + result);
										String result1 = result.replace("\"",
												"");
										if (result1.trim().equals("200")) {
											ContentValues recHedSyncUpdate = new ContentValues();
											recHedSyncUpdate.put("SyncState",
													"1");
											mydb.update(
													FPRECHED_TABLE,
													recHedSyncUpdate,
													"SyncState ='0' AND ActiveState !='1'",
													null);

											ContentValues recDetSyncUpdate = new ContentValues();
											recDetSyncUpdate.put("SyncState",
													"1");
											mydb.update(FPRECDET_TABLE,
													recDetSyncUpdate,
													"SyncState ='0'", null);
										}

									} catch (Exception e) {
									}
								}
							} catch (Exception e) {
							}
						}
					}
				}
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			mProgressDialog.dismiss();
			Cursor getRecordNotUpFInvHed = null;
			// *******Secondry Invoice********
			try {
				getRecordNotUpFInvHed = mydb.query(FORDHED_TABLE, null,
						"syncHed ='0' AND Active_State !='1'", null, null,
						null, null);
			} catch (Exception e) {
			}
			if (getRecordNotUpFInvHed != null) {
				if (getRecordNotUpFInvHed.getCount() > 0) {
					while (getRecordNotUpFInvHed.moveToNext()) {
						int fInvHedNotUpCount = getRecordNotUpFInvHed
								.getCount();
						String uploadingInvoice = Integer
								.toString(fInvHedCount);
						String uploadingFailInvoice = Integer
								.toString(fInvHedNotUpCount);
						SIupSummary = "SI :" + "(" + uploadingFailInvoice + "/"
								+ uploadingInvoice + ")";
					}
				}
			}

			if (SIupSummary == null) {
				SIupSummary = "(SO - 0/0)";
			} else if (SIupSummary == null) {
				SIupSummary = "(SO - 0/0)";
			}

			final AlertDialog alertDialog = new AlertDialog.Builder(
					DM_BBM_InvoiceMenu.this).create();
			// Setting Dialog Title
			alertDialog.setTitle("UPLOAD STATUS");
			// Setting Dialog Message
			alertDialog.setMessage(SIupSummary + "Upload Completed");
			// Setting Icon to Dialog
			alertDialog.setIcon(R.drawable.warning);
			// Setting OK Button
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					fInvHedCount = 0;
					fOrdHedCount = 0;
					fInvHedCountFail = 0;
					fOrdHedCountFail = 0;
					alertDialog.dismiss();
				}
			});
			// Showing Alert Message
			alertDialog.show();
			alertDialog.setCanceledOnTouchOutside(false);
			return;
		}
	}

	protected void checkCurrentServerDB() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectServerDB = null;
		try {
			selectServerDB = mydb.query(USER_SETTINGS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (selectServerDB != null) {
			if (selectServerDB.getCount() > 0) {
				while (selectServerDB.moveToNext()) {
					currentUserServerDB = selectServerDB.getString(7);
					Log.v(TAG, "currentUserServerDB:" + currentUserServerDB);
				}
			}
		}
		selectServerDB.close();
		mydb.close();
	}

	// Retrieve Current URL
	private void getConnectionUrl() {
		// TODO Auto-generated method stub
		Cursor getserverurl = null;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		try {
			getserverurl = mydb.query(SERVER_DETAILS, null, null, null, null,
					null, null);
		} catch (Exception e) {
		}
		if (getserverurl != null) {
			if (getserverurl.getCount() > 0) {
				while (getserverurl.moveToNext()) {
					connectionURL = getserverurl.getString(1);
					Log.v(TAG, "connectionURL:" + connectionURL);
				}
			}
		}
		mydb.close();
	}

	private void currentuserTemp() {
		// TODO Auto-generated method stub
		SQLiteDatabase mydb;
		mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE, null);
		Cursor selectCurrentuserrec = null;
		try {
			selectCurrentuserrec = mydb.query(USER_SETTINGS, null, null, null,
					null, null, null);
		} catch (Exception e) {
		}
		if (selectCurrentuserrec != null) {
			if (selectCurrentuserrec.getCount() > 0) {
				while (selectCurrentuserrec.moveToNext()) {
					username = selectCurrentuserrec.getString(1);
					lrepprefix = selectCurrentuserrec.getString(2);
					lreploccode = selectCurrentuserrec.getString(3);
					serverDbName = selectCurrentuserrec.getString(7);
					printerMac = selectCurrentuserrec.getString(5);
				}
			}
		}

		selectCurrentuserrec.close();
		mydb.close();
	}

	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onBackPressed() {
		// Do Here what ever you want do on back press;
	}

	// Display Network connection Fail Alert
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		final AlertDialog alertDialog = new AlertDialog.Builder(context)
				.create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// new DownloadAdministrative().execute();
				alertDialog.dismiss();
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	// handler for the background updating
	Handler progressHandler = new Handler() {
		public void handleMessage(Message msg) {
			Log.v(TAG, "Array Length XXX :" + arrayLength);
			mProgressDialog.incrementProgressBy(arrayLength);
		}
	};

	/********** Download Master Details *************/

	// DownloadJSON AsyncTask
	private class SyncMasterDetails extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			// Create a progressdialog
			mProgressDialog = new ProgressDialog(DM_BBM_InvoiceMenu.this);
			mProgressDialog.setMax(100);
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			// Set progressdialog title
			mProgressDialog.setTitle("Downloading Details");
			// Set progressdialog message
			mProgressDialog.setMessage("Loading Details...");
			mProgressDialog.setIndeterminate(false);
			// Show progressdialog
			mProgressDialog.show();
		}

		// *****************Background Process**************************
		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub

			// *****Download Server Databases*****
			try {
				// Replace it with your own WCF service path
				checkNetwork();
				URL json = new URL(
						connectionURL
								+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/GetdatabaseNames/mobile123");
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(
						new InputStreamReader(jc.getInputStream()));
				String line = readerfdblist.readLine();
				JSONObject jsonResponse = new JSONObject(line);
				JSONArray jsonArray = jsonResponse
						.getJSONArray("GetdatabaseNamesResult");
				for (int i = 0; i < jsonArray.length(); i++) {
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String sdbname = jObject.getString("Name");
					mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,
							null);
					ContentValues newrowdblist = new ContentValues();
					Cursor sdblistrows = null;
					try {
						sdblistrows = mydb.query(SERVER_DB_LIST, null,
								"sdbname ='" + sdbname + "'", null, null, null,
								null);
					} catch (Exception e) {
					}
					if (sdblistrows != null) {
						if (sdblistrows.getCount() >= 1) {
							while (sdblistrows.moveToNext()) {
								Log.v(TAG, "Excisting fServer DB 1 :" + sdbname);
							}
						} else {
							Log.v(TAG, "INSERT SERVER DB(1):" + i + "="
									+ sdbname.trim());
							newrowdblist.put("sdbname", sdbname.trim());
							mydb.insert(SERVER_DB_LIST, null, newrowdblist);
							sdblistrows.close();
							mydb.close();
						}
					}
					sdblistrows.close();
					mydb.close();
				}
				arrayLength = 4;
				progressHandler.sendMessage(progressHandler.obtainMessage());

			} catch (Exception e) {
			}

			// *****************Download Free Items Quentity**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItemLocFreeQty/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemLocFreeQtyResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String FreeQty = json_data.getString("FreeQty");
						String ItemCode = json_data.getString("ItemCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues insertItemFreeQty = new ContentValues();
						Cursor readItemFreeQty = null;
						try {
							readItemFreeQty = mydb.query(FITEMFREQTY_TABLE,
									null, "ItemCode ='" + ItemCode + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (readItemFreeQty != null) {
							if (readItemFreeQty.getCount() >= 1) {
								while (readItemFreeQty.moveToNext()) {
									Log.v(TAG, "Excit Free Qty (2):" + ItemCode);
								}
							} else {
								Log.v(TAG, "INSERT FreeQty(2):" + i + " = "
										+ ItemCode);
								insertItemFreeQty
										.put("FreeQty", FreeQty.trim());
								insertItemFreeQty.put("ItemCode",
										ItemCode.trim());
								mydb.insert(FITEMFREQTY_TABLE, null,
										insertItemFreeQty);
								readItemFreeQty.close();
							}
						}
						readItemFreeQty.close();
						mydb.close();

					}
					arrayLength = 6;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			// *****************Download FbrandResult Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FBrand/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FbrandResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String BrandCode = json_data.getString("BrandCode");
						String BrandName = json_data.getString("BrandName");
						String AddUser = json_data.getString("AddUser");
						String AddMach = json_data.getString("AddMach");
						String RecordId = json_data.getString("RecordId");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfBrand = new ContentValues();
						Cursor fBrandrows = null;
						try {
							fBrandrows = mydb.query(FBRAND_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fBrandrows != null) {
							if (fBrandrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fBrand (3)");
							} else {
								Log.v(TAG, "INSERT fBrand(3) :" + i + " = "
										+ RecordId.trim());
								newrowfBrand.put("BrandCode", BrandCode.trim());
								newrowfBrand.put("BrandName", BrandName.trim());
								newrowfBrand.put("AddUser", AddUser.trim());
								newrowfBrand.put("AddDate", "");
								newrowfBrand.put("AddMach", AddMach.trim());
								newrowfBrand.put("RecordId", RecordId.trim());
								mydb.insert(FBRAND_TABLE, null, newrowfBrand);
								fBrandrows.close();
								mydb.close();
							}
						}
						fBrandrows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			// *****************Download FCompanysetting Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FCompanysetting/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fCompanySettingResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String cSettingsCode = json_data
								.getString("cSettingsCode");
						String cSettingGrp = json_data.getString("cSettingGrp");
						String cLocationChar = json_data
								.getString("cLocationChar");
						String cCharVal = json_data.getString("cCharVal");
						String nNumVal = json_data.getString("nNumVal");
						String cRemarks = json_data.getString("cRemarks");
						String nType = json_data.getString("nType");
						String bUpdateFlag = json_data.getString("bUpdateFlag");
						String cCompanyCode = json_data
								.getString("cCompanyCode");
						String recordid = json_data.getString("recordid");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfCompanySetting = new ContentValues();
						Cursor fCompanySettingrows = null;
						try {
							fCompanySettingrows = mydb.query(
									FCOMPANYSETTINGS_TABLE, null, "recordid ='"
											+ recordid.trim() + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (fCompanySettingrows != null) {
							if (fCompanySettingrows.getCount() >= 1) {
								Log.v(TAG, "Excisting FCompanysetting (4)");
							} else {
								Log.v(TAG, "INSERT FCompanysetting(4) :" + i
										+ " = " + cSettingsCode.trim());
								newrowfCompanySetting.put("cSettingsCode",
										cSettingsCode.trim());
								newrowfCompanySetting.put("cSettingGrp",
										cSettingGrp.trim());
								newrowfCompanySetting.put("cLocationChar",
										cLocationChar.trim());
								newrowfCompanySetting.put("cCharVal",
										cCharVal.trim());
								newrowfCompanySetting.put("nNumVal",
										nNumVal.trim());
								newrowfCompanySetting.put("cRemarks",
										cRemarks.trim());
								newrowfCompanySetting.put("nType ",
										nType.trim());
								newrowfCompanySetting.put("bUpdateFlag",
										bUpdateFlag.trim());
								newrowfCompanySetting.put("cCompanyCode",
										cCompanyCode.trim());
								newrowfCompanySetting.put("recordid",
										recordid.trim());
								mydb.insert(FCOMPANYSETTINGS_TABLE, null,
										newrowfCompanySetting);
								fCompanySettingrows.close();
								mydb.close();
							}
						}

						fCompanySettingrows.close();
						mydb.close();
					}
					arrayLength = 3;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download fCurrencyResult**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FCurrency/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fCurrencyResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String CurCode = json_data.getString("CurCode");
						String CurDesc = json_data.getString("CurDesc");
						String RecordId = json_data.getString("RecordId");
						String fromrate = json_data.getString("fromrate");
						String torate = json_data.getString("torate");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfCurrency = new ContentValues();
						Cursor fCurrencyrows = null;
						try {
							fCurrencyrows = mydb.query(FCURRENCY_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fCurrencyrows != null) {
							if (fCurrencyrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fCurrency (5)");
							} else {
								Log.v(TAG, "INSERT fCurrency (5) :" + i + "="
										+ RecordId.trim());
								newrowfCurrency.put("CurCode", CurCode.trim());
								newrowfCurrency.put("CurDesc", CurDesc.trim());
								newrowfCurrency
										.put("fromrate", fromrate.trim());
								newrowfCurrency.put("torate", torate.trim());
								newrowfCurrency.put("AddUser", AddUser.trim());
								newrowfCurrency.put("AddDate", AddDate.trim());
								newrowfCurrency.put("AddMach", AddMach.trim());
								newrowfCurrency
										.put("recordid", RecordId.trim());
								mydb.insert(FCURRENCY_TABLE, null,
										newrowfCurrency);
								fCurrencyrows.close();
								mydb.close();
							}
						}

						fCurrencyrows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}

			// *****************Download Debtor Detaails**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/Fdebtor/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FdebtorResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String DebCode = json_data.getString("DebCode");
						String DebName = json_data.getString("DebName");
						String DebAdd1 = json_data.getString("DebAdd1");
						String DebAdd2 = json_data.getString("DebAdd2");
						String DebAdd3 = json_data.getString("DebAdd3");
						String DebTele = json_data.getString("DebTele");
						String DebMob = json_data.getString("DebMob");
						String Status = json_data.getString("Status");
						String DelPersn = json_data.getString("DelPersn");
						String DelEmail = json_data.getString("DelEmail");
						String AreaCode = json_data.getString("AreaCode");
						String CrdPeriod = json_data.getString("CrdPeriod");
						String CrdLimit = json_data.getString("CrdLimit");
						String RepCode = json_data.getString("RepCode");
						String TaxReg = json_data.getString("TaxReg");
						String PrilCode = json_data.getString("PrilCode");
						String RecordId = json_data.getString("recordid");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfdebtord = new ContentValues();
						Cursor fdebtorduserrows = null;
						try {
							fdebtorduserrows = mydb.query(FDEBTOR_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fdebtorduserrows != null) {
							if (fdebtorduserrows.getCount() >= 1) {
								Log.v(TAG, "Excisting Debtor(6) :");
							} else {
								Log.v(TAG,
										"INSERT Debtor(6) :" + RecordId.trim());
								newrowfdebtord.put("DebCode", DebCode.trim());
								newrowfdebtord.put("DebName", DebName.trim());
								newrowfdebtord.put("DebAdd1", DebAdd1.trim());
								newrowfdebtord.put("DebAdd2", DebAdd2.trim());
								newrowfdebtord.put("DebAdd3", DebAdd3.trim());
								newrowfdebtord.put("DebTele", DebTele.trim());
								newrowfdebtord.put("DebMob", DebMob.trim());
								newrowfdebtord.put("DelEmail", DelEmail.trim());
								newrowfdebtord.put("Status", Status.trim());
								newrowfdebtord.put("DelPersn", DelPersn.trim());
								newrowfdebtord.put("TaxReg", TaxReg.trim());
								newrowfdebtord.put("RecordId", RecordId.trim());
								newrowfdebtord.put("AreaCode", AreaCode.trim());
								newrowfdebtord.put("CrdPeriod",
										CrdPeriod.trim());
								newrowfdebtord.put("CrdLimit", CrdLimit.trim());
								newrowfdebtord.put("RepCode", RepCode.trim());
								newrowfdebtord.put("PrilCode", PrilCode.trim());
								newrowfdebtord.put("AreaName", "");
								mydb.insert(FDEBTOR_TABLE, null, newrowfdebtord);
								fdebtorduserrows.close();
								mydb.close();
							}
						}

						fdebtorduserrows.close();
						mydb.close();
					}
					arrayLength = 7;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download fItems Result**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItems/mobile123/"
											+ serverDbName));

					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemsResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String ItemCode = json_data.getString("ItemCode");
						String ItemName = json_data.getString("ItemName");
						String PurDesc = json_data.getString("PurDesc");
						String GroupCode = json_data.getString("GroupCode");
						String TypeCode = json_data.getString("TypeCode");
						String BrandCode = json_data.getString("BrandCode");
						String TaxComCode = json_data.getString("TaxComCode");
						String UnitCode = json_data.getString("UnitCode");
						String PackSize = json_data.getString("PackSize");
						String ReOrderLvl = json_data.getString("ReOrderLvl");
						String ReOrderQty = json_data.getString("ReOrderQty");
						String AvgPrice = json_data.getString("AvgPrice");
						String PrilCode = json_data.getString("PrilCode");
						String AddDate = json_data.getString("AddDate");
						String RecordId = json_data.getString("RecordId");
						String CatCode = json_data.getString("CatCode");
						String cosacc = json_data.getString("cosacc");
						String packing = json_data.getString("packing");
						String ItemStatus = json_data.getString("ItemStatus");
						String CurrentFreeQuantity = "0";
						
						
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						Cursor cursorfreeQty = null;
						try {
							cursorfreeQty = mydb.query(FITEMFREQTY_TABLE,
									null, "ItemCode ='" + ItemCode.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (cursorfreeQty != null) {
							if (cursorfreeQty.getCount() > 0) {
								while (cursorfreeQty.moveToNext()) {
									CurrentFreeQuantity = cursorfreeQty.getString(2);
								}
							}
							else{
								CurrentFreeQuantity = "0";
							}
						}
						
						
						
						
						ContentValues newrowfItems = new ContentValues();
						Cursor newrowfItemListuserrows = null;
						try {
							newrowfItemListuserrows = mydb.query(FITEMS_TABLE,
									null,
									"ItemCode ='" + ItemCode.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowfItemListuserrows != null) {
							if (newrowfItemListuserrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fItems (7)");
							} else {

								Log.v(TAG, "INSERT fItems(7) :" + i + "="
										+ ItemCode.trim());
								newrowfItems.put("ItemCode", ItemCode.trim());
								newrowfItems.put("ItemName", ItemName.trim());
								newrowfItems.put("BrandCode", BrandCode.trim());
								newrowfItems.put("TaxComCode",
										TaxComCode.trim());
								newrowfItems.put("PackSize", PackSize.trim());
								newrowfItems.put("ReOrderQty",
										ReOrderQty.trim());
								newrowfItems.put("AvgPrice", AvgPrice.trim());
								newrowfItems.put("PrilCode", PrilCode.trim());
								newrowfItems.put("AddDate", AddDate.trim());
								newrowfItems.put("packing", packing.trim());
								newrowfItems.put("RecordId", RecordId.trim());
								newrowfItems.put("PurDesc", PurDesc.trim());
								newrowfItems.put("TypeCode", TypeCode.trim());
								newrowfItems.put("UnitCode", UnitCode.trim());
								newrowfItems.put("ReOrderLvl",
										ReOrderLvl.trim());
								newrowfItems.put("CatCode", CatCode.trim());
								newrowfItems.put("cosacc", cosacc.trim());
								newrowfItems.put("GroupCode", GroupCode.trim());
								newrowfItems.put("itemsummary", ItemCode.trim()
										+ " " + ItemName.trim());
								newrowfItems.put("ItemStatus",
										ItemStatus.trim());
								newrowfItems.put("FreeItems", CurrentFreeQuantity);
								mydb.insert(FITEMS_TABLE, null, newrowfItems);
								newrowfItemListuserrows.close();
								mydb.close();
							}
						}

						newrowfItemListuserrows.close();
						mydb.close();

					}
					arrayLength = 8;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download FLocation details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fLocations/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fLocationsResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String LocCode = json_data.getString("LocCode");
						String LocName = json_data.getString("LocName");
						String TeleNo = json_data.getString("TeleNo");
						String FaxNo = json_data.getString("FaxNo");
						String EMail = json_data.getString("EMail");
						String LoctCode = json_data.getString("LoctCode");
						String Contact = json_data.getString("Contact");
						String Address1 = json_data.getString("Address1");
						String Address2 = json_data.getString("Address2");
						String Address3 = json_data.getString("Address3");
						String AddUser = json_data.getString("AddUser");
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String RecordId = json_data.getString("RecordId");
						String prefix = json_data.getString("prefix");
						String cSettingsCode = json_data
								.getString("cSettingsCode");
						String ProfCen = json_data.getString("ProfCen");
						String cSettingsCde2 = json_data
								.getString("cSettingsCde2");
						String CostCode = json_data.getString("CostCode");
						String AccCode = json_data.getString("AccCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowflocation = new ContentValues();
						Cursor newrowflocationrows = null;
						try {
							newrowflocationrows = mydb.query(FLOCATION_TABLE,
									null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowflocationrows != null) {
							if (newrowflocationrows.getCount() >= 1) {
								Log.v(TAG, "Excisting FLocation(8)");
							} else {
								Log.v(TAG,
										"INSERT FLocation(8) :"
												+ RecordId.trim());
								newrowflocation.put("LocCode", LocCode.trim());
								newrowflocation.put("LocName", LocName.trim());
								newrowflocation.put("TeleNo", TeleNo.trim());
								newrowflocation.put("FaxNo", FaxNo.trim());
								newrowflocation.put("EMail", EMail.trim());
								newrowflocation
										.put("LoctCode", LoctCode.trim());
								newrowflocation.put("Contact", Contact.trim());
								newrowflocation
										.put("Address1", Address1.trim());
								newrowflocation
										.put("Address2", Address2.trim());
								newrowflocation
										.put("Address3", Address3.trim());
								newrowflocation.put("AddUser", AddUser.trim());
								newrowflocation.put("AddDate", AddDate.trim());
								newrowflocation.put("AddMach", AddMach.trim());
								newrowflocation
										.put("RecordId", RecordId.trim());
								newrowflocation.put("prefix", prefix.trim());
								newrowflocation.put("cSettingsCode",
										cSettingsCode.trim());
								newrowflocation.put("ProfCen", ProfCen.trim());
								newrowflocation.put("cSettingsCde2",
										cSettingsCde2.trim());
								newrowflocation
										.put("CostCode", CostCode.trim());
								newrowflocation.put("AccCode", AccCode.trim());
								mydb.insert(FLOCATION_TABLE, null,
										newrowflocation);
								newrowflocationrows.close();
								mydb.close();
							}
						}

						newrowflocationrows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download FSalRep Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FSalRep/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fSalRepResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String RepCode = json_data.getString("RepCode");
						String RepName = json_data.getString("RepName");
						String RepIdNo = json_data.getString("RepIdNo");
						String RepAdd1 = json_data.getString("RepAdd1");
						String RepAdd2 = json_data.getString("RepAdd2");
						String RepAdd3 = json_data.getString("RepAdd3");
						String RepTele = json_data.getString("RepTele");
						String RepMobil = json_data.getString("RepMobil");
						String RepEMail = json_data.getString("RepEMail");
						String AddUser = json_data.getString("AddUser");
						String AddMach = json_data.getString("AddMach");
						String AddDate = json_data.getString("AddDate");
						String RecordId = json_data.getString("RecordId");
						String RepPrefix = json_data.getString("RepPrefix");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowreaderfSalReprows = new ContentValues();
						Cursor newrowfSalReprows = null;
						try {
							newrowfSalReprows = mydb.query(FSALREP_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowfSalReprows != null) {
							if (newrowfSalReprows.getCount() >= 1) {
								Log.v(TAG, "Excisting fSalRep (9)");
							} else {
								Log.v(TAG, "INSERT fSalRep(9) :" + i + "="
										+ RepCode.trim());
								newrowreaderfSalReprows.put("RepCode", RepCode
										.trim().toUpperCase());
								newrowreaderfSalReprows.put("RepName",
										RepName.trim());
								newrowreaderfSalReprows.put("RepIdNo",
										RepIdNo.trim());
								newrowreaderfSalReprows.put("RepAdd1",
										RepAdd1.trim());
								newrowreaderfSalReprows.put("RepAdd2",
										RepAdd2.trim());
								newrowreaderfSalReprows.put("RepAdd3",
										RepAdd3.trim());
								newrowreaderfSalReprows.put("RepTele",
										RepTele.trim());
								newrowreaderfSalReprows.put("RepMobil",
										RepMobil.trim());
								newrowreaderfSalReprows.put("RepEMail",
										RepEMail.trim());
								newrowreaderfSalReprows.put("AddUser",
										AddUser.trim());
								newrowreaderfSalReprows.put("AddMach",
										AddMach.trim());
								newrowreaderfSalReprows.put("AddDate",
										AddDate.trim());
								newrowreaderfSalReprows.put("RecordId",
										RecordId.trim());
								newrowreaderfSalReprows.put("RepPrefix",
										RepPrefix.trim());
								mydb.insert(FSALREP_TABLE, null,
										newrowreaderfSalReprows);
								newrowfSalReprows.close();
								mydb.close();
							}
						}

						newrowfSalReprows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);

			}
			// *****************Download fTaxDetResult Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FtaxDet/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fTaxDetResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String TaxComCode = json_data.getString("TaxComCode");
						String TaxCode = json_data.getString("TaxCode");
						String TaxRate = json_data.getString("TaxRate");
						String TaxMode = json_data.getString("TaxMode");
						String TaxSeq = json_data.getString("TaxSeq");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfTaxDet = new ContentValues();
						Cursor fTaxDetrows = null;
						try {
							fTaxDetrows = mydb.query(FTAXDET_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fTaxDetrows != null) {
							if (fTaxDetrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fTaxDet(10)");
							} else {
								Log.v(TAG, "INSERT fTaxDet(10) :" + i + "="
										+ RecordId.trim());
								newrowfTaxDet.put("TaxComCode",
										TaxComCode.trim());
								newrowfTaxDet.put("TaxCode", TaxCode.trim());
								newrowfTaxDet.put("TaxRate", TaxRate.trim());
								newrowfTaxDet.put("TaxMode", TaxMode.trim());
								newrowfTaxDet.put("TaxSeq", TaxSeq.trim());
								newrowfTaxDet.put("RecordId", RecordId.trim());
								mydb.insert(FTAXDET_TABLE, null, newrowfTaxDet);
								fTaxDetrows.close();
								mydb.close();
							}
						}

						fTaxDetrows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			// *****************Download fItemPri Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fItemPri/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fItemPriResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String PrilCode = json_data.getString("PrilCode");
						String Price = json_data.getString("Price");
						String ItemCode = json_data.getString("ItemCode");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfItemPri = new ContentValues();
						Cursor fItemPri = null;
						try {
							fItemPri = mydb.query(
									FITEMPRI_TABLE,
									null,
									"ItemCode ='" + ItemCode.trim()
											+ "' AND PrilCode ='"
											+ PrilCode.trim() + "'", null,
									null, null, null);
						} catch (Exception e) {
						}
						if (fItemPri != null) {
							if (fItemPri.getCount() >= 1) {
								Log.v(TAG, "Excisting fItemPri(11)");
							} else {
								Log.v(TAG, "Insert fItemPri(11):" + PrilCode);
								newrowfItemPri.put("PrilCode", PrilCode.trim());
								newrowfItemPri.put("Price", Price.trim());
								newrowfItemPri.put("ItemCode", ItemCode.trim());
								mydb.insert(FITEMPRI_TABLE, null,
										newrowfItemPri);
								fItemPri.close();
								mydb.close();
							}
						}

						fItemPri.close();
						mydb.close();
					}
					arrayLength = 6;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// *****************Download fTax Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fTax/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace("{\"fTaxResult\":[{",
								"[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String TaxCode = json_data.getString("TaxCode");
						String TaxDevd = json_data.getString("TaxDevd");
						String TaxName = json_data.getString("TaxName");
						String TaxPayAcc = json_data.getString("TaxPayAcc");
						String TaxPer = json_data.getString("TaxPer");
						String TaxRecAcc = json_data.getString("TaxRecAcc");
						String TaxRegNo = json_data.getString("TaxRegNo");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfTax = new ContentValues();
						Cursor curfTax = null;
						try {
							curfTax = mydb.query(FTAX_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (curfTax != null) {
							if (curfTax.getCount() >= 1) {
								Log.v(TAG, "Excisting fTax(12)");
							} else {
								Log.v(TAG, "Insert fTax(12):" + TaxCode);
								newrowfTax.put("AddDate", AddDate.trim());
								newrowfTax.put("TaxCode", TaxCode.trim());
								newrowfTax.put("TaxDevd", TaxDevd.trim());
								newrowfTax.put("TaxDevd", TaxDevd.trim());
								newrowfTax.put("TaxName", TaxName.trim());
								newrowfTax.put("TaxPayAcc", TaxPayAcc.trim());
								newrowfTax.put("TaxPer", TaxPer.trim());
								newrowfTax.put("TaxRecAcc", TaxRecAcc.trim());
								newrowfTax.put("TaxRegNo", TaxRegNo.trim());
								newrowfTax.put("RecordId", RecordId.trim());
								mydb.insert(FTAX_TABLE, null, newrowfTax);
								curfTax.close();
								mydb.close();
							}
						}

						curfTax.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// *****************Download fTaxHed Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fTaxHed/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fTaxHedResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String Active = json_data.getString("Active");
						String AddDate = json_data.getString("AddDate");
						String TaxComCode = json_data.getString("TaxComCode");
						String TaxComName = json_data.getString("TaxComName");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowftaxhed = new ContentValues();
						Cursor ftaxhed = null;
						try {
							ftaxhed = mydb.query(FTAXHED_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (ftaxhed != null) {
							if (ftaxhed.getCount() >= 1) {
								Log.v(TAG, "Excisting fTaxHedResult(13)");
							} else {
								Log.v(TAG, "Insert fTaxHedResult(13):"
										+ RecordId);
								newrowftaxhed.put("Active", Active.trim());
								newrowftaxhed.put("AddDate", AddDate.trim());
								newrowftaxhed.put("TaxComCode",
										TaxComCode.trim());
								newrowftaxhed.put("TaxComName",
										TaxComName.trim());
								newrowftaxhed.put("RecordId", RecordId.trim());
								mydb.insert(FTAXHED_TABLE, null, newrowftaxhed);
								ftaxhed.close();
								mydb.close();
							}
						}

						ftaxhed.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// *****************Download fControl Details**************
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fControl/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fControlResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AdCntAcc = json_data.getString("AdCntAcc");
						String AutoAst = json_data.getString("AutoAst");
						String BalgCrLm = json_data.getString("BalgCrLm");
						String ComAdd1 = json_data.getString("ComAdd1");
						String ComAdd2 = json_data.getString("ComAdd2");
						String ComName = json_data.getString("ComName");
						String Comgainlos = json_data.getString("Comgainlos");
						String ContTxn = json_data.getString("ConfTxn");
						String CrosAccFlg = json_data.getString("CrosAccFlg");
						String DealCode = json_data.getString("DealCode");
						String IntegPrefx = json_data.getString("IntegPrefx");
						String IntegSeqNo = json_data.getString("IntegSeqNo");
						String NbtCmTaxNo = json_data.getString("NbtCmTaxNo");
						String RecordId = json_data.getString("RecordId");
						String SysId = json_data.getString("SysId");
						String Tranlock = json_data.getString("Tranlock");
						String VatCmTaxNo = json_data.getString("VatCmTaxNo");
						String aRetEarn = json_data.getString("aRetEarn");
						String basecur = json_data.getString("basecur");
						String comRegNo = json_data.getString("comRegNo");
						String comemail = json_data.getString("comemail");
						String comfax1 = json_data.getString("comfax1");
						String comgstac = json_data.getString("comgstac");
						String comtel1 = json_data.getString("comtel1");
						String comtel2 = json_data.getString("comtel2");
						String comweb = json_data.getString("comweb");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfcontrol = new ContentValues();
						Cursor curfcontrol = null;
						try {
							curfcontrol = mydb.query(FCONTROL_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (curfcontrol != null) {
							if (curfcontrol.getCount() >= 1) {
								Log.v(TAG, "Excisting RecordId(14)");
							} else {
								Log.v(TAG, "Insert RecordId(14):" + RecordId);
								newrowfcontrol.put("AdCntAcc", AdCntAcc.trim());
								newrowfcontrol.put("AutoAst", AutoAst.trim());
								newrowfcontrol.put("BalgCrLm", BalgCrLm.trim());
								newrowfcontrol.put("ComAdd1", ComAdd1.trim());
								newrowfcontrol.put("ComAdd2", ComAdd2.trim());
								newrowfcontrol.put("ComName", ComName.trim());
								newrowfcontrol.put("Comgainlos",
										Comgainlos.trim());
								newrowfcontrol.put("ContTxn", ContTxn.trim());
								newrowfcontrol.put("CrosAccFlg",
										CrosAccFlg.trim());
								newrowfcontrol.put("DealCode", DealCode.trim());
								newrowfcontrol.put("IntegPrefx",
										IntegPrefx.trim());
								newrowfcontrol.put("IntegSeqNo",
										IntegSeqNo.trim());
								newrowfcontrol.put("NbtCmTaxNo",
										NbtCmTaxNo.trim());
								newrowfcontrol.put("RecordId", RecordId.trim());
								newrowfcontrol.put("SysId", SysId.trim());
								newrowfcontrol.put("Tranlock", Tranlock.trim());
								newrowfcontrol.put("VatCmTaxNo",
										VatCmTaxNo.trim());
								newrowfcontrol.put("aRetEarn", aRetEarn.trim());
								newrowfcontrol.put("basecur", basecur.trim());
								newrowfcontrol.put("comRegNo", comRegNo.trim());
								newrowfcontrol.put("comemail", comemail.trim());
								newrowfcontrol.put("comfax1", comfax1.trim());
								newrowfcontrol.put("comgstac", comgstac.trim());
								newrowfcontrol.put("comtel1", comtel1.trim());
								newrowfcontrol.put("comtel2", comtel2.trim());
								newrowfcontrol.put("comweb", comweb.trim());
								mydb.insert(FCONTROL_TABLE, null,
										newrowfcontrol);
								curfcontrol.close();
								mydb.close();
							}
						}

						curfcontrol.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			// ********************* Download FCompanyBranch Details
			// *******************************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/FCompanyBranch/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FCompanyBranchResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String cSettingsCode = json_data
								.getString("cSettingsCode");
						String BranchCode = json_data.getString("BranchCode");
						String nNumVal = json_data.getString("nNumVal");
						String RecordId = json_data.getString("RecordId");
						String nMonth = json_data.getString("nMonth");
						String nYear = json_data.getString("nYear");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfbranch = new ContentValues();
						Cursor fCompanyBranch = null;
						try {
							fCompanyBranch = mydb.query(FCOMPANYBRANCH_TABLE,
									null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fCompanyBranch != null) {
							if (fCompanyBranch.getCount() >= 1) {
								Log.v(TAG, "Excisting fCompanyBranch(15)");

							} else {
								Log.v(TAG, "Insert fCompanyBranch(15):"
										+ RecordId);
								newrowfbranch.put("cSettingsCodefb",
										cSettingsCode.trim());
								newrowfbranch.put("BranchCode",
										BranchCode.trim());
								newrowfbranch.put("nNumValfb", nNumVal.trim());
								newrowfbranch.put("RecordId", RecordId.trim());
								newrowfbranch.put("nMonthb", nMonth.trim());
								newrowfbranch.put("nYearb", nYear.trim());
								mydb.insert(FCOMPANYBRANCH_TABLE, null,
										newrowfbranch);
								fCompanyBranch.close();
								mydb.close();
							}
						}

						fCompanyBranch.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// ********************* Download Fdebtax Details
			// *******************************//*
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/Fdebtax/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"FdebtaxResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String DebCode = json_data.getString("DebCode");
						String RecordId = json_data.getString("RecordId");
						String TaxCode = json_data.getString("TaxCode");
						String TaxRegNo = json_data.getString("TaxRegNo");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfdebtax = new ContentValues();
						Cursor fDebTax = null;
						try {
							fDebTax = mydb.query(FDEBTAX_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fDebTax != null) {
							if (fDebTax.getCount() >= 1) {
								Log.v(TAG, "Excisting FdebtaxResult(16)");

							} else {
								Log.v(TAG, "Insert FdebtaxResult(16):"
										+ RecordId);
								newrowfdebtax.put("DebCode", DebCode.trim());
								newrowfdebtax.put("RecordId", RecordId.trim());
								newrowfdebtax.put("TaxCode", TaxCode.trim());
								newrowfdebtax.put("TaxRegNo", TaxRegNo.trim());
								mydb.insert(FDEBTAX_TABLE, null, newrowfdebtax);
								fDebTax.close();
								mydb.close();
							}
						}

						fDebTax.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			// ********************* Download fCompanyDM Details
			// *******************************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fCompanyDM/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fCompanyDMResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}
					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String cSettingsCodedm = json_data
								.getString("cSettingsCode");
						String nMonth = json_data.getString("nMonth");
						String nYear = json_data.getString("nYear");
						String nNumVal = json_data.getString("nNumVal");
						String recordid = json_data.getString("recordid");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfCompanyDM = new ContentValues();
						Cursor fCompanyDM = null;
						try {
							fCompanyDM = mydb.query(FCOMPANYDM_TABLE, null,
									"recordid ='" + recordid.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fCompanyDM != null) {
							if (fCompanyDM.getCount() >= 1) {
								Log.v(TAG, "Excisting fCompanyDMResult(15)");

							} else {
								Log.v(TAG, "Insert fCompanyDMResult(15):"
										+ recordid);
								newrowfCompanyDM.put("cSettingsCodedm",
										cSettingsCodedm.trim());
								newrowfCompanyDM.put("nMonth", nMonth.trim());
								newrowfCompanyDM.put("nYear", nYear.trim());
								newrowfCompanyDM.put("nNumValdm",
										nNumVal.trim());
								newrowfCompanyDM.put("recordid",
										recordid.trim());
								mydb.insert(FCOMPANYDM_TABLE, null,
										newrowfCompanyDM);
								fCompanyDM.close();
								mydb.close();
							}
						}

						fCompanyDM.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			/************ Download fArea Table *****************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fArea/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace("{\"fAreaResult\":[{",
								"[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String AreaCode = json_data.getString("AreaCode");
						String AreaName = json_data.getString("AreaName");
						String RecordId = json_data.getString("RecordId");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfArea = new ContentValues();
						Cursor fAreaDetrows = null;
						try {
							fAreaDetrows = mydb.query(FAREA_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fAreaDetrows != null) {
							if (fAreaDetrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fArea(16)");
							} else {
								Log.v(TAG, "INSERT fArea(16) :" + i + "="
										+ RecordId.trim());
								newrowfArea.put("AddDate", AddDate.trim());
								newrowfArea.put("AddMach", AddMach.trim());
								newrowfArea.put("AddUser", AddUser.trim());
								newrowfArea.put("AreaCode", AreaCode.trim());
								newrowfArea.put("AreaName", AreaName.trim());
								newrowfArea.put("RecordId", RecordId.trim());

								try {
									ContentValues updateDebtor = new ContentValues();
									updateDebtor.put("AreaName",
											AreaName.trim());
									mydb.update(FDEBTOR_TABLE, updateDebtor,
											"AreaCode ='" + AreaCode + "'",
											null);
								} catch (Exception e) {

								}

								mydb.insert(FAREA_TABLE, null, newrowfArea);
								fAreaDetrows.close();
								mydb.close();
							}
						}

						fAreaDetrows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());
				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			/*********** fDDBNote Table ********************/

			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fddbnote/mobile123/"
											+ serverDbName));

					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";

						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();

						String FresultA = result.replace(
								"{\"fDdbNoteResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}

					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String Amt = json_data.getString("Amt");
						String BAmt = json_data.getString("BAmt");
						String CurCode = json_data.getString("CurCode");
						String DebCode = json_data.getString("DebCode");
						String ManuRef = json_data.getString("ManuRef");
						String RecordId = json_data.getString("RecordId");
						String RefNo = json_data.getString("RefNo");
						String Remarks = json_data.getString("Remarks");
						String RepCode = json_data.getString("RepCode");
						String TotBal = json_data.getString("TotBal");
						String TxnDate = json_data.getString("TxnDate");
						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfddbnote = new ContentValues();
						Cursor fddbnoteDetrows = null;
						try {
							fddbnoteDetrows = mydb.query(FDDBNOTE_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fddbnoteDetrows != null) {
							if (fddbnoteDetrows.getCount() >= 1) {
								Log.v(TAG, "Excisting fddbnote(17)");
							} else {
								Log.v(TAG, "INSERT fddbnote(17) :" + i + "="
										+ RecordId.trim());
								newrowfddbnote.put("RefNo", RefNo.trim());
								newrowfddbnote.put("TxnDate", TxnDate.trim());
								newrowfddbnote.put("BAmt", BAmt.trim());
								newrowfddbnote.put("DebCode", DebCode.trim());
								newrowfddbnote.put("RecordId", RecordId.trim());
								newrowfddbnote.put("ManuRef", ManuRef.trim());
								newrowfddbnote.put("Curcode", CurCode.trim());
								newrowfddbnote.put("Amt", Amt.trim());
								newrowfddbnote.put("Totbal", TotBal.trim());
								newrowfddbnote.put("Remarks", Remarks.trim());
								newrowfddbnote.put("RepCode", RepCode.trim());
								mydb.insert(FDDBNOTE_TABLE, null,
										newrowfddbnote);
								fddbnoteDetrows.close();
								mydb.close();
							}
						}

						fddbnoteDetrows.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			/************ fBank Details ************************/
			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fbank/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();
						String FresultA = result.replace("{\"fbankResult\":[{",
								"[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}
					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String Branch = json_data.getString("Branch");
						String RecordId = json_data.getString("RecordId");
						String bankaccno = json_data.getString("bankaccno");
						String bankadd1 = json_data.getString("bankadd1");
						String bankadd2 = json_data.getString("bankadd2");
						String bankcode = json_data.getString("bankcode");
						String bankname = json_data.getString("bankname");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfbank = new ContentValues();
						Cursor fbankDM = null;
						try {
							fbankDM = mydb.query(FBANK_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (fbankDM != null) {
							if (fbankDM.getCount() >= 1) {
								Log.v(TAG, "Excisting fbankDM(18)");

							} else {
								Log.v(TAG, "Insert fbankDM(18):" + RecordId);
								newrowfbank.put("AddDate", AddDate.trim());
								newrowfbank.put("AddMach", AddMach.trim());
								newrowfbank.put("AddUser", AddUser.trim());
								newrowfbank.put("Branch", Branch.trim());
								newrowfbank.put("RecordId", RecordId.trim());
								newrowfbank.put("bankaccno", bankaccno.trim());
								newrowfbank.put("bankadd1", bankadd1.trim());
								newrowfbank.put("bankadd2", bankadd2.trim());
								newrowfbank.put("bankcode", bankcode.trim());
								newrowfbank.put("bankname", bankname.trim());
								mydb.insert(FBANK_TABLE, null, newrowfbank);
								fbankDM.close();
								mydb.close();
							}
						}

						fbankDM.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}

			/***************** fglfacc Details *******************/

			try {
				DefaultHttpClient httpClient = new DefaultHttpClient();
				try {
					HttpResponse response = httpClient
							.execute(new HttpGet(
									connectionURL
											+ "/PDADBWebServiceBBM/PDADBWebServiceRest.svc/fglfacc/mobile123/"
											+ serverDbName));
					InputStream is = response.getEntity().getContent();
					if (is != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(is, "iso-8859-1"), 8);
						sb = new StringBuilder();
						sb.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sb.append(line + "\n");
						}
						result = sb.toString();
						String FresultA = result.replace(
								"{\"fglfaccResult\":[{", "[{");
						FresultB = FresultA.replace("}]}", "}]");
						// convert String into InputStream
						isNew = new ByteArrayInputStream(FresultB.getBytes());

					}
					if (isNew != null) {
						BufferedReader reader = new BufferedReader(
								new InputStreamReader(isNew, "iso-8859-1"), 8);
						sbNew = new StringBuilder();
						sbNew.append(reader.readLine() + "\n");
						String line = "0";
						while ((line = reader.readLine()) != null) {
							sbNew.append(line + "\n");
						}
						resultNew = sbNew.toString();
					}
					jArray = new JSONArray(resultNew);
					JSONObject json_data = null;
					for (int i = 0; i < jArray.length(); i++) {
						json_data = jArray.getJSONObject(i);

						String AccCat = json_data.getString("AccCat");
						String AccCode = json_data.getString("AccCode");
						String AccDesc = json_data.getString("AccDesc");
						String AccTyp = json_data.getString("AccTyp");
						String AddDate = json_data.getString("AddDate");
						String AddMach = json_data.getString("AddMach");
						String AddUser = json_data.getString("AddUser");
						String BankChg = json_data.getString("BankChg");
						String ConAcc = json_data.getString("ConAcc");
						String CostCode = json_data.getString("CostCode");
						String CurCode = json_data.getString("CurCode");
						String NoteCode = json_data.getString("NoteCode");
						String NumGen = json_data.getString("NumGen");
						String RecordId = json_data.getString("RecordId");
						String SortCode = json_data.getString("SortCode");
						String SubnNote = json_data.getString("SubnNote");

						mydb = openOrCreateDatabase(DBNAME,
								Context.MODE_PRIVATE, null);
						ContentValues newrowfglfacc = new ContentValues();
						Cursor newrowfglfaccDM = null;
						try {
							newrowfglfaccDM = mydb.query(FGLFACC_TABLE, null,
									"RecordId ='" + RecordId.trim() + "'",
									null, null, null, null);
						} catch (Exception e) {
						}
						if (newrowfglfaccDM != null) {
							if (newrowfglfaccDM.getCount() >= 1) {
								Log.v(TAG, "Excisting newrowfglfaccDM(19)");

							} else {
								Log.v(TAG, "Insert newrowfglfaccDM(19):"
										+ RecordId);
								newrowfglfacc.put("AccCat", AccCat.trim());
								newrowfglfacc.put("AccCode", AccCode.trim());
								newrowfglfacc.put("AccDesc", AccDesc.trim());
								newrowfglfacc.put("AccTyp", AccTyp.trim());
								newrowfglfacc.put("AddDate", AddDate.trim());
								newrowfglfacc.put("AddMach", AddMach.trim());
								newrowfglfacc.put("AddUser", AddUser.trim());
								newrowfglfacc.put("BankChg", BankChg.trim());
								newrowfglfacc.put("ConAcc", ConAcc.trim());
								newrowfglfacc.put("CostCode", CostCode.trim());
								newrowfglfacc.put("CurCode", CurCode.trim());
								newrowfglfacc.put("NoteCode", NoteCode.trim());
								newrowfglfacc.put("NumGen", NumGen.trim());
								newrowfglfacc.put("RecordId", RecordId.trim());
								newrowfglfacc.put("SortCode", SortCode.trim());
								newrowfglfacc.put("SubnNote", SubnNote.trim());

								mydb.insert(FGLFACC_TABLE, null, newrowfglfacc);
								newrowfglfaccDM.close();
								mydb.close();
							}
						}

						newrowfglfaccDM.close();
						mydb.close();
					}
					arrayLength = 4;
					progressHandler
							.sendMessage(progressHandler.obtainMessage());

				} catch (Exception e) {
					e.printStackTrace();
					Log.d("", "exception1 : " + e);
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Log.d("", "exception2 : " + e);
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			if (NetFail == 0) {
				mProgressDialog.dismiss();
				// arrayLength = 100;
				try {
					showDialog(DIALOG_SYNC_SUCCESS);
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			} else if (NetFail == 404) {
				countDownActivator();
			}

		}

	}

	/*
	 * public void checkNetwork(){ isInternetPresent =
	 * cd.isConnectingToInternet(); if (isInternetPresent) { NetFail = 0; }
	 * else{ NetFail = 404; } }
	 */
	public void checkNetwork() {
		// TODO Auto-generated method stub
		isInternetPresent = cd.isConnectingToInternet();

		// check for Internet status
		if (isInternetPresent) {
			// Internet Connection is Present
			// make HTTP requests
			Log.v(TAG, "Net Work Present........");
			NetFail = 0;
		} else {
			// Internet connection is not present
			// Ask user to connect to Internet
			// showAlertDialog(DM_InvoiceMenu.this, "No Internet Connection",
			// "You don't have internet connection.", false);
			Log.v(TAG, "Net Work Disabled........");
			NetFail = 404;
			countDownActivator();
		}
	}

	private void countDownActivator() {
		// TODO Auto-generated method stub
		mCountDown = new CountDownTimer(30000, 1000) {

			@Override
			public void onFinish() {
				mProgressDialog.dismiss();
				showAlertDialog(
						DM_BBM_InvoiceMenu.this,
						"Internet Connection Lost..",
						"Your Internet Connection Lost During Syncing.Data Sync Not Completed. Tap OK to Continue Sync..",
						false);
			}

			@Override
			public void onTick(long millisUntilFinished) {
				Log.v(TAG, "Time Remaining Chk 1:" + millisUntilFinished / 1000);
				isInternetPresent = cd.isConnectingToInternet();

				// check for Internet status
				if (isInternetPresent) {
					NetFail = 0;
					arrayLength = 0;
					// Internet Connection is Present
					// Stop coun down
					mCountDown.cancel();
				} else {
					// Internet connection is not present

				}
			}
		}.start();
	}

	// Handling Dialog Box Functions
	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {
		case DIALOG_SYNC_SUCCESS:
			LayoutInflater inflater = LayoutInflater.from(this);
			View dialogview = inflater.inflate(
					R.layout.dm_bbm_dialog_sync_success, null);

			AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
			dialogbuilder.setTitle("Sync Data Completed. Select SalesRef...");
			dialogbuilder.setView(dialogview);
			InvoiceHeaderAlert = dialogbuilder.create();
			InvoiceHeaderAlert.setCanceledOnTouchOutside(false);
			break;
		}
		return InvoiceHeaderAlert;
	}

	public void SyncCompleteAccept(View view) {
		Intent myIntent = new Intent(view.getContext(),
				DM_BBM_InvoiceMenu.class);
		myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
				| Intent.FLAG_ACTIVITY_NEW_TASK);
		myIntent.putExtra("TAGID", "RELOAD");
		startActivityForResult(myIntent, 0);
		finish();
		return;
	}
}
